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');