Search code examples
phpooppropertiesoverloadingmagic-methods

Call method upon setting a declared public property


The problem I have is the __set() magic method, by design, only works for undeclared properties. Is there a __set() like solution for declared properties where I can call upon a method when a property is set? Properties being declared would greatly increase the ease of use for the classes I am designing, especially for IDEs.


Solution

  • No, you can't use any of the magic for properties and methods declared or visible in the current scope. Php only invokes them if it cannot find the declaration in the class. That's what the documentation says about it:

    The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope.

    But you can help most IDEs, PhpStorm in particular, I'm sure Netbeans also supports it, by providing the PHPDoc for the class with the properties and methods:

    /**
     * @property string $myProperty
     * @method string myMethod(int $param = 10)
     */
    class MyClass
    {
    }