Magic function in PHP

EngrHasanuzzamanSumo 12 views 16 slides Sep 15, 2022
Slide 1
Slide 1 of 16
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16

About This Presentation

Magic methods in PHP like __get(), __set(), __call()


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

References https://www.php.net/manual/en/language.oop5.magic.php https://liamhammett.com/laravel-mixins-KEzjmLrx https://dev.to/nvio/laravel-greatest-trick-revealed-magic-methods-31om https://www.php.net/manual/en/function.call-user-func-array.php https://www.php.net/manual/en/closure.bindto.php

END