通过参数引用名称获取受保护的属性?

时间:2012-05-31 21:52:26

标签: php object protected

让我们说:

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

但是它不起作用,它不可能吗?它没有返回任何内容或显示错误

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分:1)

它运行正常,但您在__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');

答案 2 :(得分:0)

我认为你应该阅读PHP的魔术方法。你正在做的事情很有可能,但你做这件事的方式可能不是最好的。

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

我认为您应该查看__get()和__set()方法。