|
Overloading
Overloading in PHP provides means to dynamically
The overloading methods are invoked when interacting with
properties or methods that have not been declared or are not
visible in
the current scope. The rest of this section will use the terms
All overloading methods must be defined as
Property overloading
public void __set(string
$name , mixed $value )public mixed __get(string
$name )public bool __isset(string
$name )public void __unset(string
$name )__set() is run when writing data to inaccessible (protected or private) or non-existing properties. __get() is utilized for reading data from inaccessible (protected or private) or non-existing properties. __isset() is triggered by calling isset or empty on inaccessible (protected or private) or non-existing properties. __unset() is invoked when unset is used on inaccessible (protected or private) or non-existing properties. The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.
Property overloading only works in object context. These magic
methods will not be triggered in static context. Therefore
these methods should not be declared
static.
A warning is issued if one of the magic overloading
methods is declared
Example #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods
The above example will output: Setting 'a' to '1' Getting 'a' 1 Is 'a' set? bool(true) Unsetting 'a' Is 'a' set? bool(false) 1 Let's experiment with the private property named 'hidden': Privates are visible inside the class, so __get() not used... 2 Privates not visible outside of class, so __get() is used... Getting 'hidden' Notice: Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29 Method overloading
public mixed __call(string
$name , array $arguments )public static mixed __callStatic(string
$name , array $arguments )__call() is triggered when invoking inaccessible methods in an object context. __callStatic() is triggered when invoking inaccessible methods in a static context. The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method. Example #2 Overloading methods via the __call() and __callStatic() methods
The above example will output: Calling object method 'runTest' in object context Calling static method 'runTest' in static context |