Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 是否通过引用名称的参数获取受保护的属性?_Php_Object_Protected - Fatal编程技术网

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

Php 是否通过引用名称的参数获取受保护的属性?,php,object,protected,Php,Object,Protected,让我们说: class myclass{ protected $info; protected $owner; __construct(){ $this->info = 'nothing'; $this->owner = 'nobody'; } function getProp($string){ return $this->$string; } } 但它不起作用,是不是不可

让我们说:

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

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

我认为您应该仔细阅读PHP的神奇方法。你所做的是很有可能的,但是你做的方式可能不是最好的


我想你应该看看uuu get()和uuu set()方法

我在您的_构造之前添加了
函数
,但除此之外,它似乎工作正常

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'

它工作正常,但缺少
\uuu construct
前面的function关键字。这将输出“无”:


对我有效(在修复了你的
\u构造
声明后。缺少
函数
关键字)。哈哈,是的,几乎是同一时间。有趣的是,我选择在
\uu构造
周围加上反勾号,而你选择在
函数
周围加上反勾号。
<?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');