The __get & __set Magical Functions in PHP PRO

Using these two functions we can dynamically add new variables, that weren’t defined in the class, to objects in our program.

<?
class Bongo
{
    var $vec;
    function __construct()
    {
        $this->vec = array();
    }
    function __get($str)
    {
        return $this->vec[$str];
    }
    function __set($var_name,$var_value)
    {
        $this->vec[$var_name] = $var_value;
    }
}

$ob = new Bongo();

$ob->name="balaboa";
$ob->id=12123123;

echo $ob->name." ".$ob->id;

?>

The following video clip shows how this code runs and provides more explanation.

Share:

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences