Magic methods in PHP like __get(), __set(), __call()
Size: 316.28 KB
Language: en
Added: Sep 15, 2022
Slides: 16 pages
Slide Content
welcome
What is magic Method? Special methods which are called implicitly as an internal steps of the PHP code executions. All the magic methods name start with __(double underscore)
List of the magic methods __get($property) __set($property, $value) __call($fun, $arg) __callStatic($fun, $arg) __construct() __destruct() __isset($content) __unset($content) __serialize() __unserialize() __sleep() __wakeup() __toString() __invoke() __set_state($array) __clone() __debugInfo()
__get($property) <?php class Foo { public $info = "this is info prop \n " ; public function __get( $property ) { echo "$property is not exist" ; } } echo ( new Foo)->info; # this is info prop ( new Foo)->random_property; # random_property is not exist
__set($property, $value) ?php class Foo { public $info = "this is info prop \n " ; public function __set($property, $value) { echo "$property is not exist" ; } } $obj = new Foo $obj ->info = “new value”; echo $obj->info; // new value $obj->bar = “this is bar”; // bar is not exist
In Laravel where are these being used? ( __get($property) & __set($property, $value)) Laravel stores all the DB columns in protected $attributes associative array When we try to access any value from db, since that property does exist on the model, php called the __get method with the property name With in __get method, laravel check passing property in the associative array and return the corresponding value
class User { protected $attributes = [ ]; public function __get(string $key) { if(!array_key_exists($key, $ attributes )) { r eturn null; } return $this->attributes[$key]; } public function __set($key, $val) { $this->attributes[$key] = $val; } } $user = new User; $user->firstName; // null $user-> firstName = 'Alice'; // $attributes = [ 'firstName' => 'Alice'] $use->lastName = “ foo ”; // $attributes = [ 'firstName' => 'Alice', “lastName” => “foo” ] property_exists( $ user , ‘ firstName’ ); // will return false
__call($name, $arguments) __call is executed when a method was called but not found in a specific class Example: <?php class Foo { public function __call( $method , $arg ) { echo "$method was called with argument $arg[0] but that method does not exist" ; } } ( new Foo)->randomMethod( 'test' ); # randomMethod was called with argument test but that method does not exist
__callStatic($name, $arg) <?php class Foo { public static function __callStatic( $name , $arg ) { echo "Static method $name is called that does not exist" ; } } Foo::random(); # Static method random is called that does not exist
How __call($name, $arguments) and __callStatic($name, $arg) are being used in the Laravel? Short answer: to provide feature like macro and facade, laravel use __call() & __callStatic() What is macro: Using macro we can add additional functionality to the Laravel internal component like: Request, Response, Collection class
Example of macro Let’s say you are working with the api and want the below response on success. { "success": true, "msg": "Your message", "data": Array() } We can create this format from the controller and send as response but that is not good solution as this is not reusable and we have to refactor every controllers if we want to change the format in future How can we create re- usable format? One way could be macro
We can create an macro and bind to any service Providers root method (ex. AppServiceProvider) public function boot() 2 { 3 Response ::macro(‘success’, function ($msg, $data) { return response()->json ([ "success" => true, "msg" => $msg, "data" => $data ]); }); 7 } // calling the macro. Response::success(“message”, []); // call as static method $response->success(“message”, []); // call as instance method
How __call($name, $arguments) and __callStatic($name, $arg) are used to create macro? Link to the laravel macroable trait: https://github.com/laravel/framework/blob/e6c8aa0e39d8f91068ad1c299546536e9f25ef63/src/Illuminate/Support/Traits/Macroable.php
When should we use these magic method? - usually not anywhere during normal application development - we might need during implementation of the Library