What is the difference between regular php functions and magic functions in php?
A generic PHP function is declared and available with the expected inputs and results, but they should be called. In contrast, magic functions are defined in PHP, but if they are defined in a class, they will be called automatically. For example, isset() is a PHP function
Determine if a variable is set and is not NULL
But __isset () is an overload of class properties .
PHP overloading provides the means to dynamically "create" properties and methods. These dynamic objects are processed using magic methods that can be set in the class for various types of actions. Overload methods are called when interacting with properties or methods that were not declared or not visible in the current area.
It will be called magically behind the scene, as described above, if announced in class. Let the experiment overload the property of the PHP class.
<?php class PropertyTest { private $data = array(); public $declared = 1; private $hidden = 2; public function __set($name, $value) { echo "Setting '$name' to '$value'\n"; $this->data[$name] = $value; } public function __get($name) { echo "Getting '$name'\n"; if (array_key_exists($name, $this->data)) { return $this->data[$name]; } $trace = debug_backtrace(); trigger_error( 'Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE); return null; } public function __isset($name) { echo "Is '$name' set?\n"; return isset($this->data[$name]); } public function __unset($name) { echo "Unsetting '$name'\n"; unset($this->data[$name]); } public function getHidden() { return $this->hidden; } } echo "<pre>\n"; $obj = new PropertyTest;
The above code outputs
Setting 'a' to '1' Getting 'a' a: 1 Is 'a' set? bool(true) Unsetting 'a' Is 'a' set? bool(false) bool(true) declared: 1 declared: 3 Is 'hidden' set? bool(false) Let experiment with the private property named 'hidden': Privates are visible inside the class, so __get() not used... 2 Privates not visible outside of class, so __get() is used... Getting 'hidden' NULL
It says that the "hidden" property is not set and shows bool(false) , but returns a value of "2" later, because the "hidden" property does not appear outside the class and calls the magic __isset() function, but it is also not set in 'data', therefore returns bool(false) . In the getHidden() function, although it returns a private property of the object that is visible to the internal objects of the object. In the last var_dump($obj->hidden) it calls the __get() method and returns NULL. Because in the __get() method, it is looking for data['hidden'] , which is NULL .
Note: here is an example from PHP Manuel: Overloading with some changes.
Hope this helps!