[PHP] what is __ means in PHP ?


Description
     Sometime in php we often seen __ (underscore) character in naming methods. why they use that ??
that's magic methods !!. magic method in php always start with underscore __. for example :

public function __sleep()
{
     //to do here
}

you cannot use this function name in any classes unless you want this magic method assosiate with your classes. so when we need magic method ? it's depend on what your need. if  you not need this magic method don't use them.

PHP have several magic method, here's the list :

__construct()
is the method name for the constructor. The constructor is called on an object after it has been created.
class CAR
{
    public $brand = '';
    public function __construct($name) 
    {
        $this->brand = $name ;    }
}

$person = new CAR ( "honda" );
echo $person->brand;

__destruct()
Destructors called during the script shutdown have HTTP headers already sent. Attempting to throw an exception from a destructor can causes a fatal error.
class CAR
{
    public function __destruct() 
    {
        print "destroy the class";    
    }
}

$person = new CAR ();

__call()
this methods will call another function that inaccessible property like private / protected. 
namespace test\foo;

class A
{
    public static function __callStatic($method, $args)
    {
        echo __METHOD__ . "\n";

        return call_user_func_array(__CLASS__ . '::' . $method, $args);
    }

    protected static function foo()
    {
        echo __METHOD__ . "\n";
    }
}

A::foo();

__callStatic()
class A {
    public function __call($method, $parameters) {
        echo "I'm the __call() magic method".PHP_EOL;
    }

    public static function __callStatic($method, $parameters) {
        echo "I'm the __callStatic() magic method".PHP_EOL;
    }
}

class B extends A {
    public function bar() {
        A::foo();
    }
}

A::foo();
(new A)->foo();

B::bar();
(new B)->bar();

Result :
I'm the __callStatic() magic method
I'm the __call() magic method
I'm the __callStatic() magic method
I'm the __call() magic method

__get()
is utilized for reading data from inaccessible properties.

__set()
is run when writing data to inaccessible properties.

__isset()

__unset()

__sleep()

__wakeup()

__toString()

__invoke()

__set_state()

__clone()

__debugInfo()

*Note :
All example i taken from google (mostly from stackoverflow). thanks to the owner whose have this code :).

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih