php magic methods - oop

I will love to discuss into details about an interesting topic of PHP magic methods:
************************************************************************
----------------------    PHP MAGIC METHODS-----------------------------------------------------
***************************************************************************
-It is a special method in a class.
-It overrides the default action when the object performs the action.
-The names of magic method starts with a double underscore(__)

Some of examples are constructor __construct() and destructor __destruct() which are invoked when an object is created or deleted respectively.

Other examples :
__call()                   triggered when invoking an inaccessible instance method.
__callStatic            triggered when invoking an inaccessible  static method.
__get()                    Invoked when reading a value from a non existing or non accessible property
__set()                    Invoked when writing a value to a non accesible property
__isSet()                 Invoked when calling isSet() or empty() on non-existing or inaccesible property
__unset()                Invoked when unSet() is called on non-existing or inaccesible method
__sleep()                commits the pending data
__wakeUp()            Invoked when the _unserialize() run to reconstruct any resource that an object may                                   have
__serialize()            calls _serialize() if its available,then construct to return an associative of                                                     key/values pairs that represent the serialized form of the object
__toString()            Invoked when an object of a class is treated as a string
__invoke()                Invoked when an object is invoked as a function
__set_state()            Called for a class exported by var_export()
__clone()                called when the cloning is complete
__debugInfo()            called by var_dump() when dumping an object to get the properties that should be shown

-------->I WILL FOCUS ONLY ON __get() and __set() METHODS 

PHP  _SET METHOD

What happens when you write to a non-existing or inaccessible property in php??
->php calls the set method automatically

here is the syntax
public __set ( string $name , mixed $value ) : void

set method accepts the name and value you write to:

here is a detailed example:

<?php

class HtmlElement
{
private $attributes = [];

private $tag;

public function __construct($tag)
{
$this->tag = $tag;
}

public function __set($name, $value)
{
$this->attributes[$name] = $value;
}

public function html($innerHTML = '')
{
$html = "<{$this->tag}";
foreach ($this->attributes as $key => $value) {
$html .= ' ' . $key . '="' . $value . '"';
}
$html .= '>';
$html .= $innerHTML;
$html .= "</$this->tag>";

return $html;
}
}

EXPLAINING THE CODE:
  • first define the HTMLElement class that has only one property $attributes.It will hold all the attribute of the html element.
  • Initialize a constructor with a tag name.Tag name can be anything like div.
  • Implement __set() method that add any property to the $attribute array
  • Define HTMLElement to return the HTML representation of the element
Using the HTMLElement class above to create a new div element

<?php

require 'HTMLElement.php';

$div = new HtmlElement('div');

$div->id = 'page';
$div->class = 'light';

echo $div->html('Hello');

Output
<div id="page" class="light">Hello</div>

Attempting to write to not existing property
$div->id = 'page';
$div->class = 'light';

php calls the __set() method implicitly to add this methods to the $attribute property

PHP __GET() METHOD:
when you try to access the property that does not exist or inaccessible property like private or protected
php automatically calls the __get() method
-It only accepts one argument which is the name of property that you want to access.
public __get ( string $name ) : mixed


the following adds the __get method to HTMLElements class
<?php

class HtmlElement
{
private $attributes = [];

private $tag;

public function __construct($tag)
{
$this->tag = $tag;
}

public function __set($name, $value)
{
$this->attributes[$name] = $value;
}

public function __get($name)
{
if (array_key_exists($name, $this->attributes)) {
return $this->attributes[$name];
}
}

public function html($innerHTML = '')
{
$html = "<{$this->tag}";
foreach ($this->attributes as $key => $value) {
$html .= ' ' . $key . '="' . $value . '"';
}
$html .= '>';
$html .= $innerHTML;
$html .= "</$this->tag>";

return $html;
}
}

The __get() methods checks whether the property exists in the $attribute before returning the results

The following creates a new article element ,sets the id and class attributes then shows the value of this attributes
<?php

require 'HTMLElement.php';

$article = new HtmlElement('article');

$article->id = 'main';
$article->class = 'light';

// show the attributes
echo $article->class; // light
echo $article->id; // main

😝😝😝😝😝😝in conclusion
1) php calls the __get() method automatically when you access a non existing or innaccesible property
2)php calls the __set() method when you assign a value a value to a non existing or innaccesible property

with your love allπŸ’–πŸ’•πŸ’•πŸ’•πŸ’•kamau waweru---------->lets make the future and advance technology with php


                               



Comments

Popular posts from this blog

CURRYING

Tips on accelerating your software engineering career

Useful learning resources