[英]What is the difference between `$this->name` and `$this->$name`?
[英]What is the difference between Php $this->$propery_name and $this->propery_name
$protected_property_name = '_'.$name;
if(property_exists($this, $protected_property_name)){
return $this->$protected_property_name;
}
我正在学习面向对象编程的教程,但是,教师提出了一个我以前从未见过的新代码结构,但没有明确解释他为什么会这样做。 如果您在if(语句)中注意到$ this - > $ protected_property_name语句有两个$符号,一个用于$ this,另一个用于$ protected_property_name,通常它应该只有$ this-> protected_property_name而没有美元符号protected_property_name变量。 当我尝试从protected_property_name变量中删除$符号时,触发了错误。 完整的代码看起来像这样
class Addrress{
protected $_postal_code;
function __get($name){
if(!$this->_postal_code){
$this->_postal_code = $this->_postal_code_guess();
}
//Attempt to return protected property by name
$protected_property_name = '_'.$name;
if(property_exists($this, $protected_property_name)){
return $this->$protected_property_name;
}
//Unable to access property; trigger error.
trigger_error('Undefined property via __get:() '. $name);
return NULL;
}
}
让我们假设我们有一个班级
class Test {
public $myAttr = 1;
}
var $x = new Test();
我们可以访问像$ x-> myAttr这样的公共属性。
如果我们在变量中有属性的名称,例如,该怎么办?
$var = 'myAttr';
我们可以使用$ x - > $ var访问属性的值
这是一个示例类:
class Example {
public $property_one = 1;
public $property_two = 2;
}
您可以看到以下代码的不同之处:
$example = new Example();
echo $example->property_one; //echo 1
$other_property = 'property_two';
echo $example->$other_property; // equal to $example->property_two and echo 2
非OOP示例:
$variable_one = 100;
$variable_name = 'variable_one';
echo $$variable_name; // equal to echo $variable_one and echo 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.