|
OverloadingOverloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. 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 "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility. All overloading methods must be defined as public.
Changelog
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 properties. __get() is utilized for reading data from inaccessible properties. __isset() is triggered by calling isset or empty on inaccessible properties. __unset() is invoked when unset is used on inaccessible 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. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.
Example #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods
<?php 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
<?php The above example will output: Calling object method 'runTest' in object context Calling static method 'runTest' in static context |