You shouldn't use magic methods in PHP unless you want some documented magic functionality.
They allow you to react to certain events when using these particular objects. This means when certain things happen to your object, you can define how it should react in that instance.
Each of these methods are triggered automatically and you are just defining what should happen under these circumstances.
Probably you won't ever need to use any of them besides __construct()
and __destruct()
when dealing with objects.
__construct()
- Is called when an object is first created. You can inject parameters and dependencies to set your object up.
__destruct()
- Is called when an object is destroyed. You can write some cleanup code here. Closing any open datastreams, database connections... whatever.
__get()
- Listens for get requests of the properties.
__set()
- Listens for set requests of the properties.
__isset()
- Triggered by calling isset() or empty() on the object's properties.
__unset()
- Triggered by calling unset() on the object's properties.
__toString()
- Allows you to define how an object will behave when it's treated like a string.
__sleep()
- Code defined here will run before you use serialize(). So you can define which properties of the object should be serialised.
__wakeup()
- This is used to reinitialize any tasks that may have been put to stop during the serialization.
__invoke()
- Defines how your class should behave if you "invoke" it and use it like a function.
__clone()
- Triggered when cloning an object is finished. (If you copy your objects they are still linked to their original as they are still referencing it. Cloning can get you a clean copy.)
__debugInfo
- Triggered when using var_dump() on the object. You can use it to control what kind of info should show up in the dump. If the method isn't defined on an object, then all public, protected and private properties will be shown.
__toString()
is when you doecho $class
repl.it/Cd6w/1__get($var)
magic method to your class. That can retrieve, sanitise and return the relevant data from the class member (private or otherwise).$myObj->foo
instead of$myObj->getFoo()
while still retaining the possibilities of a function call. If you extend "magic methods" to includeArrayAccess
andIterable
it allows you some polymorphic possibilities like$myObj['foo']
andforeach ($myObj as ...)
.