Skip to content

Commit daf859a

Browse files
committed
update magic methods
1 parent cbe2d2d commit daf859a

File tree

2 files changed

+288
-2
lines changed

2 files changed

+288
-2
lines changed

README.md

Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,22 @@ OOP in a nutshell in PHP
1515
- [Type Hinting](#type-hinting)
1616
- [Static Method and Property](#static-method-and-property)
1717
- [Trait](#trait)
18+
- [All magic methods overview](#all-magic-methods-overview)
19+
- [__construct](#__construct)
20+
- [__destruct](#__destruct)
21+
- [__call](#__call)
22+
- [__callStatic](#__callStatic)
23+
- [__get](#__get)
24+
- [__set](#__set)
25+
- [__isset](#__isset)
26+
- [__unset](#__unset)
27+
- [__sleep](#__sleep)
28+
- [__wakeup](#__wakeup)
29+
- [__toString](#__toString)
30+
- [__invoke](#__invoke)
31+
- [__set_state](#__set_state)
32+
- [__debuginfo](#__debuginfo)
33+
- [__clone](#__clone)
1834

1935
### Class, Object, Method and Property
2036

@@ -225,6 +241,8 @@ $car1 = new Car('Mercedes');
225241

226242
echo $car1->getCarModel();
227243
```
244+
[⏬ All magic methods overview](#all-magic-methods-overview)
245+
228246
[🔝 Back to contents](#table-of-contents)
229247

230248
## Inheritance
@@ -611,5 +629,273 @@ $o = new MyHelloWorld();
611629
$o->sayHello();
612630
$o->sayWorld();
613631
$o->sayExclamationMark();
632+
```
633+
[🔝 Back to contents](#table-of-contents)
634+
635+
### All Magic Methods Overview
636+
637+
### __construct
638+
- The PHP constructor is the first method that is automatically called after the object is created.
639+
- Each class has a constructor. If you do not explicitly declare it, then there will be a default constructor with no parameters and empty content in the class.
640+
- Constructors are usually used to perform some initialization tasks, such as setting initial values ​​for member variables when creating objects.
641+
- Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private)
642+
643+
### __destruct
644+
- Destructor is the opposite of constructor.
645+
The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
646+
- Destructor allows you to perform some operations before destroying an object, such as closing a file, emptying a result set, and so on.
647+
- In general, the destructor is not very common in PHP. It's an optional part of a class, usually used to complete some cleanup tasks before the object is destroyed.
648+
- Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body. Also like constructors, a child class may inherit the parent's destructor if it does not implement one itself.
649+
650+
### __call
651+
- Triggered when invoking inaccessible methods in an object context, simply when method is not found in that class
652+
- This method takes two parameters. The first parameter $name argument is the name of the method being called and the second $arguments will receive multiple arguments of the method as an array.
653+
654+
### __callStatic
655+
- Triggered when invoking inaccessible methods in a static context, simply when static method is not found in that class
656+
- This method takes two parameters. The first parameter $name argument is the name of the method being called and the second $arguments will receive multiple arguments of the method as an array.
657+
658+
### __get
659+
- We can use the magic method __get() to access a private property of an external object
660+
661+
### __set
662+
- It is used to set the private property of the object.
663+
- When an undefined property is assigned, the __set() method will be triggered and the passed parameters are the property name and value that are set.
664+
665+
### __isset
666+
- It is triggered when we call isset() or empty() on inaccessible properties
667+
668+
### __unset
669+
- It is triggered when we call unset() on inaccessible properties
670+
671+
### __sleep
672+
- The serialize() method will check if there is a magic method __sleep() in the class. If it exists, the method will be called first and then perform the serialize operation.
673+
- The __sleep() method is often used to specify the properties that need to be serialized before saving data. If there are some very large objects that don't need to be saved all, then you will find this feature is very useful.
674+
- It is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
675+
- It is not possible for __sleep() to return names of private properties in parent classes
676+
677+
### __wakeup
678+
- In contrast to the __sleep() method, the __wakeup() method is often used in deserialize operations, such as re-building a database connection, or performing other initialization operations.
679+
- This will invoke destruct method internally
680+
681+
### __toString
682+
- The __toString() method will be called when using echo method to print an object directly.
683+
- This method must return a string, otherwise it will throw a fatal error.
684+
685+
### __invoke
686+
- This method is called when a we try to call an object as a function.
687+
688+
### __set_state
689+
- This static method is called for classes exported by var_export()
690+
- The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).
691+
692+
### __debuginfo
693+
- This method is called by var_dump() when dumping an object to get the properties that should be shown.
694+
- If the method isn't defined on an object, then all public, protected and private properties will be shown.
695+
696+
### __clone
697+
- An object copy is created by using the clone keyword (which calls the object's __clone() method if possible).
698+
- An object's __clone() method cannot be called directly.
699+
- When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.
700+
- Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
701+
702+
703+
```php
704+
<?php
705+
// We are implementing Serializable only for testing serialize() and unserialize()
706+
class Car implements Serializable
707+
{
708+
public $name;
709+
private $hidden = 'Serect';
710+
711+
// __construct ([ mixed $args = "" [, $... ]] ) : void
712+
function __construct($name = null)
713+
{
714+
$this->name = $name;
715+
echo ("Constructor is called\n");
716+
}
717+
718+
public function say()
719+
{
720+
echo "My name is $this->name\n";
721+
}
722+
723+
// __destruct ( void ) : void
724+
function __destruct()
725+
{
726+
echo "Destroying " . __class__ . "\n";
727+
}
728+
729+
// public __call ( string $name , array $arguments ) : mixed
730+
public function __call($name, $arguments)
731+
{
732+
echo "Calling object method '$name', Arguments: " . implode(', ', $arguments) . "\n";
733+
}
734+
735+
// public static __callStatic ( string $name , array $arguments ) : mixed
736+
public static function __callStatic($name, $arguments)
737+
{
738+
echo "Calling static method '$name', Arguments: " . implode(', ', $arguments) . "\n";
739+
}
740+
741+
// public __set ( string $name , mixed $value ) : void
742+
public function __set($name, $value)
743+
{
744+
echo "Setting '$name' to '$value'\n";
745+
$this->$name = $value;
746+
}
747+
748+
// public __get ( string $name ) : mixed
749+
public function __get($name)
750+
{
751+
echo "Getting '$name'\n";
752+
return $this->$name;
753+
}
754+
755+
// public __isset ( string $name ) : bool
756+
public function __isset($name)
757+
{
758+
echo "Is '$name' set?\n";
759+
return isset($this->$name);
760+
}
761+
762+
// public __unset ( string $name ) : void
763+
public function __unset($name)
764+
{
765+
echo "Unsetting '$name'\n";
766+
unset($this->$name);
767+
}
768+
769+
// public __sleep ( void ) : array
770+
public function __sleep()
771+
{
772+
echo "It is invoked because serialize() method is invoked outside the class\n";
773+
$this->name = base64_encode($this->name);
774+
// should return an array
775+
return array('name');
776+
}
777+
778+
public function __wakeup()
779+
{
780+
echo "It is invoked when the unserialize() method is invoked outside the class.<br>";
781+
$this->name = 'Mr. Bean';
782+
// There is no need to return an array here.
783+
}
784+
785+
// Serializable interface method
786+
public function serialize()
787+
{
788+
return serialize('hello world');
789+
}
790+
791+
// Serializable interface method
792+
public function unserialize($serialized)
793+
{
794+
$this->name = unserialize($serialized);
795+
}
796+
797+
// public __toString ( void ) : string
798+
public function __toString()
799+
{
800+
return "Beautiful Car\n";
801+
}
802+
803+
// __invoke ([ $... ] ) : mixed
804+
public function __invoke($x = true)
805+
{
806+
var_dump($x);
807+
}
808+
809+
// static __set_state ( array $properties ) : object
810+
public static function __set_state($an_array)
811+
{
812+
$obj = new Car;
813+
$obj->name = $an_array["name"];
814+
815+
return $obj;
816+
}
817+
818+
// __debugInfo ( void ) : array
819+
public function __debugInfo()
820+
{
821+
return ['name' => 'Debug Name'];
822+
}
823+
824+
// __clone ( void ) : void
825+
public function __clone()
826+
{
827+
echo "You are cloning the object\n";
828+
}
829+
830+
}
831+
832+
// __construct is invoked
833+
$bmw = new Car('X1');
834+
// say() method from class is invoked
835+
$bmw->say();
836+
// class has no method names runTest() so __call is invoked
837+
$bmw->runTest('Hi', 123);
838+
// class has no static method names runTest() so __callStatic is invoked
839+
Car::runTest('Hello', 123);
840+
echo "\n";
841+
842+
// class has no private property 'aaa' so __set is invoked
843+
$bmw->aaa = 1;
844+
// class has private property 'hidden' so __set is invoked
845+
$bmw->hidden = "Hacked";
846+
// class has public property 'name' so __set is not invoked
847+
$bmw->name = "X8";
848+
echo "\n";
849+
850+
// class has no private property 'aaa' so __get is not invoked
851+
echo $bmw->aaa . "\n";
852+
// class has private property 'hidden' so __get is invoked
853+
echo $bmw->hidden . "\n";
854+
// class has public property 'name' so __get is invoked
855+
echo $bmw->name . "\n";
856+
echo "\n";
857+
858+
// class has private property 'hidden' so __isset is invoked
859+
var_dump(isset($bmw->hidden));
860+
// class has private property 'hidden' so __unset is invoked
861+
unset($bmw->hidden);
862+
var_dump(isset($bmw->hidden));
863+
echo "\n";
864+
865+
// class has public property 'name' so __isset is not invoked
866+
var_dump(isset($bmw->name));
867+
// class has public property 'name' so __unset is not invoked
868+
unset($bmw->name);
869+
// Now 'name' property isn't set, that's why __isset is invoked to search it's private properties
870+
var_dump(isset($bmw->name));
871+
echo "\n";
872+
873+
// serialize will invoke __sleep method
874+
echo(serialize($bmw));
875+
// unserialize will invoke __wakeup method
876+
// it will also invoke __destruct method
877+
echo(unserialize(serialize($bmw)));
878+
echo "\n";
879+
880+
// The __toString() method will be called when using echo method to print an object directly.
881+
echo $bmw;
882+
// When you try to call an object in the way of calling a function, the __invoke method will be called automatically.
883+
echo $bmw();
884+
echo "\n";
885+
886+
// __set_state() method is called by var_export()
887+
$someCar = new Car('Some Name');
888+
$someCar->name = "Honda";
889+
eval('$b = ' . var_export($someCar, true) . ';');
890+
echo var_export($b);
891+
echo "\n";
892+
893+
// __debugInfo() method is called by var_dump() when dumping an object to get the properties that should be shown
894+
var_dump(new Car("poll"));
895+
echo "\n";
896+
897+
// __clone() method will be called when performing clone
898+
$fromSomeCar = clone $someCar;
899+
614900
```
615901
[🔝 Back to contents](#table-of-contents)

files/14 All Magic Methods Overview.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,10 +168,10 @@ public function __clone()
168168
echo "\n";
169169

170170
// serialize will invoke __sleep method
171-
echo(serialize($bmw));
171+
echo (serialize($bmw));
172172
// unserialize will invoke __wakeup method
173173
// it will also invoke __destruct method
174-
echo(unserialize(serialize($bmw)));
174+
echo (unserialize(serialize($bmw)));
175175
echo "\n";
176176

177177
// The __toString() method will be called when using echo method to print an object directly.

0 commit comments

Comments
 (0)