本文介绍了访问PHP对象属性的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问PHP对象的属性?

此外,使用访问对象的属性有什么区别$this->$property1$this->property1?

Also, what is the difference between accessing an object's property with$this->$property1 vs. $this->property1?

当我尝试使用$this->$property1时,出现以下错误:

When I try to use $this->$property1 I get the following error:

PHP关于对象属性的文档有一条评论提到了这一点,但该评论并未真正深入解释.

PHP's documentation on object properties has one comment which mentions this, but the comment doesn't really explain in depth.

推荐答案

  1. $property1//特定变量
  2. $this->property1//特定属性
  1. $property1 // specific variable
  2. $this->property1 // specific attribute

在类上的一般用法是不使用"$",否则您将调用一个名为$property1的变量,该变量可以具有任何值.

The general use on classes is without "$" otherwise you are calling a variable called $property1 that could take any value.

示例:

class X {
  public $property1 = 'Value 1';
  public $property2 = 'Value 2';
}
$property1 = 'property2';  //Name of attribute 2
$x_object = new X();
echo $x_object->property1; //Return 'Value 1'
echo $x_object->$property1; //Return 'Value 2'

这篇关于访问PHP对象属性的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 00:46