My question is rather simple, here is the context:
http://php.net/manual/en/language.oop5.magic.php
Magic Methods
The function names
__construct()
,__destruct()
,__call()
,__callStatic()
,__get()
,__set()
,__isset()
,__unset()
,__sleep()
,__wakeup()
, __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
I get what these methods are for and how to use them. What I don't understand is this:
...unless you want some documented magic functionality.
What does that even mean? Are there actual reasons to create user defined __magicMethods()
?
__invoke(): This method is defined in a class that will be called while trying to call an object in a way of calling function.
Magic methods are special methods in python that have double underscores (dunder) on both sides of the method name. Magic methods are predominantly used for operator overloading.
Magic methods are special methods which override PHP's default's action when certain actions are performed on an object. Caution. All methods names starting with __ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.
Another aspect of PHP overloading capabilities is property overloading. There are four magic methods that support property overloading: __get(), __set(), __isset() and __unset().
I think that they only mean that it's better not to use __
as a starting name for your methods because PHP has reserved that convention for his magic methods and if you do use that for a method it might get overriden in the future and have some magic functionality. At least that's how i understood that
EDIT - to be even clearer: Let's say thatyou implement for your own business logic a method called __toNumber()
. In a future version of PHP they decide that whenever an object is used as a number (maybe when you do $result = 3 * $yourObject
) the magic method __toNumber()
will be invoked...your object will have some "Magic" documented functionality even if you didn't specifically add it
It means never use names that starts with __
for functions unless you want the magic functionality documented in the PHP manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With