Domanda

Is there a way to have the __set method in the abstract class be executed if the variable being changed is declared in the abstract class and run a different __set if the variable being changed belongs to the class extending the abstract class. I'm sure I'm going about this the wrong way, any help would be appreciated it.

abstract class abstract_class {
    protected $protected_var;

    function __set($name, $value)
    {
        echo "abstract __set";
    }
}

class regular_class extends abstract_class {
    private $temp;

    function __set($name, $value)
    {
        echo "regular __set";
    }
}

$class = new regular_class();
$class->protected_var = "value";

In the above example, I would want "abstract __set" to be outputted instead of "regular __set" being outputted.

È stato utile?

Soluzione

class Base
{
    protected $a = "a";

    public function __set($name, $value)
    {
        echo "base";
    }
}

class Child extends Base
{
    private $b = "b";
    public function __set($name, $value)
    {
        if (property_exists(get_parent_class(), $name))
            parent::__set($name, $value);
        else
            echo "child";
    }
}

$obj = new Child();

$obj->a = 1;
$obj->b = 1;

here is solution

remember, always when you create child of any class and want to overload __set, you need 1st to check if property is in parent class otherwise it won't work properly

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top