access property of object

To access public property of object in php, just use $obj->propertyname like:

class MyClass
{
  public $a;
};

$my=new MyClass;
$my->a=1;
echo $my->a;

Note that, unlike C++, you cannot use MyClass $my to create an instance of a class. You must use $my=new MyClass to initialize an object.

Unlike C++, you do not need to declare a variable in a class to use it:

class MyClass
{
};

$my=new MyClass;
$my->a=1;
echo $my->a;

When accessing an undeclared property, the __set function, if defined, will be called:

class MyClass
{
    public function __set($name,$value)//called
    {
        echo "set $name<br>";
        return $this->$name=$value;
    }
};

$my=new MyClass;
$my->a=1;
echo $my->a;

This does not apply to a declared (public) property:

class MyClass
{
    public $a;
    public function __set($name,$value) //not called
    {
        echo "set $name<br>";
        return $this->$name=$value;
    }
};

$my=new MyClass;
$my->a=1;
echo $my->a;

But the __set function is called when writing to a (declared) private/protected property:

class MyClass
{
    private $a;
    public function __set($name,$value) // called
    {
        echo "set $name<br>";
        return $this->$name=$value;
    }
};

$my=new MyClass;
$my->a=1;
echo $my->a;//fatal error

The reading of the private/protected property still fails with a fatal error. To read a private/protected property using the $obj->propertyname syntax, you need a getter function:

class MyClass
{
    private $a;
    
    public function __get($name)
    {
        echo "get $name<br>";
        return $this->a;
    }
    public function __set($name,$value) // called
    {
        echo "set $name<br>";
        return $this->$name=$value;
    }
};

$my=new MyClass;
$my->a=1;
echo $my->a;

Note that the setter function takes exactly two arguments, and the getter function must take exactly 1 argument, and we did not call the setter function __set and the getter function __get explicitly. They are called implicitly.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply