gpt4 book ai didi

php - Php $this->$propery_name 和 $this->propery_name 有什么区别

转载 作者:可可西里 更新时间:2023-11-01 00:29:18 24 4
gpt4 key购买 nike

    $protected_property_name = '_'.$name;
if(property_exists($this, $protected_property_name)){
return $this->$protected_property_name;
}

我正在学习面向对象编程的教程,但是,讲师提出了一种我以前从未见过的新代码结构,但没有明确解释他这样做的原因。如果您在 if(statement) 中注意到$this->$protected_property_name 语句有两个 $ 符号,一个用于 $this,另一个用于 $protected_property_name 通常它应该只是$this->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 这样的公共(public)属性。

如果我们在变量中有属性的名称,比如

$var = 'myAttr';

我们可以用$x->$var访问属性的值

关于php - Php $this->$propery_name 和 $this->propery_name 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44404685/

24 4 0
文章推荐: javascript -