回应PHP类属性

can somebody explain to me why the property $message is null before the method 'getMessage'?

I was expecting it to return 'this is a message' but it returns null, it only returns a string once I reset it in the method.

Cheers

<?php

class Data {
    public $message = 'this is a message';

    public function getMessage() {
        return $this->$message = 'new value';
    }
}

$object = new Data;

var_dump($object->$getMessage); // Equals Null

echo $object->getMessage(); // Equals 'New value'

There is no variable $getMessage defined, yet you're trying to use it as though it was a property name; so of course it can't return anything

If you assigned a value to $getMessage, e.g.

$getMessage = 'message';

then using

$object->$getMessage

will treat this as $object->message (like a variable variable) to point to the message property


Then in your getMessage() method, you have

return $this->$message = 'new value';

which will use the value of the variable $message (which isn't defined) and use it like a variable variable again to set a property named by that (non-existent) value.


To reference the message properties in the class, it's $this->message, not $this->$message

class Data {
    public $message = 'this is a message';

    public function getMessage() {
        return $this->message = 'new value'; // Access internal variable $message
    }
}

$object = new Data;

var_dump($object->message); // Equals 'this is a message'
echo $object->getMessage(); // Equals 'new value'

getMessage is not a property its a method, similar to a function, you can't output a function.

you can read more about properties here.

here a quick example of using properties and methods:

<?php 

 class example {

  // this is a property 
  public $a = 10;
  // this is a private property
  // private properties cannot be accessed outside the object
  private $b = 15;    

  // this is a method 
  public function sum(Int $a, Int $b) : Int
  {
      return $a + $b;
  }

  // this is a method to get the private propery 
  public function getB() : Int 
  {
     return $this->b;
  }

  }

  $obj = new example();
  // note you don't put '$' before the property name
  $a   = $obj->a;
  //$b   = $obj->b; // this will cause an error !    
  $b   = $obj->getB(); // works ! 
  $sum = $obj->sum($a,$b); // works !  
  echo $sum;