What is the access syntax for PHP object properties?
P粉966335669
P粉966335669 2023-08-22 19:45:26
0
2
504

How to access the properties of a PHP object?

Also, what is the difference between accessing object properties using $this->$property1 and $this->property1?

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

'PHP: Cannot access null property'.

There is a comment in PHP's object properties documentation that mentions this problem, but the comment does not explain it in detail.

P粉966335669
P粉966335669

reply all (2)
P粉143640496

$this->property1means:

Use the object and get the variables bound to the object property1

$this->$property1means:

Evaluate the string $property1 and use the result to obtain a variable named by the $property1 result, which is bound to the object

    P粉336536706
    1. $property1//Specific variable
    2. $this->property1//Specific property

    In the normal usage of the class, there is no need to use"$", otherwise you will call a variable named$property1, which can take any value.

    Example:

    class X { public $property1 = 'Value 1'; public $property2 = 'Value 2'; } $property1 = 'property2'; // 属性2的名称 $x_object = new X(); echo $x_object->property1; // 返回 'Value 1' echo $x_object->$property1; // 返回 'Value 2'
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!