Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and using magic methods within PHP

I am trying to get to grips with PHP's magic methods, and for this I am creating a test class that looks as follows:

<?php
class overload
{
    protected $lastCalledParam;

    public $param;

    public function __construct() 
    {
        return $this->switchConstruct(func_get_args());
    }

    protected function switchConstruct(array $args)
    {
        switch (count($args))
        {
            case 0:
                return print "0 params<br />";
            case 1:
                return call_user_func_array(array($this, 'constr1'), $args);
            case 2:
                return call_user_func_array(array($this, 'constr2'), $args);
        }
        die("Invalid number of args");  
    }

    protected function constr1($a) 
    {
        print "constr1 called<br />";
    }

    protected function constr2($a, $b) 
    {
        print "constr2 called<br />";
    }

    public function __get($name)
    {
        $this->lastCalledParam = $name;
        return $this->{$name};
    }

    public function __set($name, $value)
    {
        $this->lastCalledParam = $name;
        $this->{$name} = $value;
    }

    protected function lastCalled()
    {
        if (func_num_args() == 1)
        {
            $args = func_get_args();
            $this->lastCalledParam = $args[0];
        }
        return $this->lastCalledParam;
    }

    public function __toString()
    {
        return $this->lastCalledParam == null ? "No data found" : $this->lastCalledParam;
    }
}

And called as such:

<?php

require_once 'clib/overload.php';

$c = new overload();
print $c->__toString();
print "<br />";
$c->param = "Hello";
print $c->__toString();
?>

The behaviour that I am expecting is that on the first __toString() call, there will be:

0 params
No data found
Hello

But what I get is:

0 params
No data found
No data found

I have come to a major sticking point with this and cannot see why it is not doing the work to set the lastCalledParam property!

I am getting a grand total of 0 errors and 0 warnings with full error and warning reporting turned on so I do no understand what is not being called, where/why.


1 Answers

__set is only invoked if the parameter cannot be reached normally. Your public $param would need to be protected at least for __set to be invoked.

__set() is run when writing data to inaccessible properties.

http://php.net/manual/en/language.oop5.overloading.php#object.set (emphasis mine)

like image 111
deceze Avatar answered Sep 22 '26 22:09

deceze