Thursday 6 September 2018

Does not show the expected result when using __get () in php


<?php
class classname
{
public $attribute;
function __get($name)
{
return 'here:'.$this->$name;
}
function __set ($name, $value)
{
$this->$name = $value;
}
}
$a = new classname();
$a->attribute = 5;
echo $a->attribute;

When I run above script, it shows:5
Question:
echo $a->attribute; this line of code will invoke function __get($name), right? so why it does not show: here:5 ?

The magic __get and __set and __call are only called if the property properties or methods are undefined or unaccessible from the calling scope, or undefined.
To make this work you will have to remove a public reference to attribute or make it protected or private.
class classname
{
  protected $attribute;
  function __get($name)
  {
    return 'here:'.$this->$name;
  }
  function __set ($name, $value)
  {
    $this->$name = $value;
  }
}
$a = new classname();
$a->attribute = 5; //  calling __set
echo $a->attribute; // calling __get

0 comments:

Post a Comment