0

まあ言ってみれば:

class myclass{
     protected $info;
     protected $owner;
     __construct(){
        $this->info = 'nothing';
        $this->owner = 'nobody';
    }
    function getProp($string){
        return $this->$string;
    }
}

しかし、それは機能していません、それは可能ではありませんか?何も返さない、またはエラーが表示されない

4

3 に答える 3

1

__constructの前に追加しましたfunctionが、それ以外は正常に機能しているようです

class myclass{
     protected $info;
     protected $owner;
     function __construct(){
        $this->info = 'nothing';
        $this->owner = 'nobody';
     }
     function getProp($string){
        return $this->$string;
     }
}

$m = new myclass();
echo $m->getProp('info');

// echos 'nothing'
于 2012-05-31T21:57:08.580 に答える
1

正常に動作しますが、の前にfunctionキーワードがありません__construct。これは「何も」を出力しません:

<?php

class myclass{
     protected $info;
     protected $owner;

    function __construct(){
        $this->info = 'nothing';
        $this->owner = 'nobody';
    }
    function getProp($string){
        return $this->$string;
    }
}

$test = new myclass();
echo $test->getProp('info');
于 2012-05-31T21:57:21.903 に答える
0

PHPの魔法のメソッドを読んでおくべきだと思います。あなたがしていることは非常に可能ですが、あなたがそれをしている方法はおそらく最善ではありません。

http://php.net/manual/en/language.oop5.magic.php

__get()メソッドと__set()メソッドを確認する必要があると思います。

于 2012-05-31T21:56:21.297 に答える