search

Home  >  Q&A  >  body text

What is the access syntax for PHP object properties?

<p><strong>How to access the properties of a PHP object? </strong></p> <p>Also, what is the difference between accessing object properties using <code>$this->$property1</code> and <code>$this->property1</code>? </p> <p>When I try to use <code>$this->$property1</code> I get the following error: </p> <blockquote> <p>'PHP: Cannot access null property'. </p> </blockquote> <p>There is a comment in PHP's object properties documentation that mentions this problem, but the comment does not explain it in detail. </p>
P粉966335669P粉966335669449 days ago640

reply all(2)I'll reply

  • P粉143640496

    P粉1436404962023-08-23 18:25:47

    $this->property1 means:

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

    $this->$property1 means:

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

    reply
    0
  • P粉336536706

    P粉3365367062023-08-23 10:46:49

    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'
    

    reply
    0
  • Cancelreply