Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

PHP OOP Tutorial from beginner to advance - (Magic Methods - Part 8)


  • Please log in to reply
No replies to this topic

#1 papabear

papabear

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 472 posts
  • Location:DarkSide

Posted 11 November 2012 - 04:47 AM

Hello everyone.. how are you doing? Welcome to the part 8 of my PHP Basic OOP Series we are now at part 8! Thank you so much for reading my tutorial even if they are not really great.
Today we are going to learn about Magic Methods in PHP. What are those Magic Methods anyway?

Magic Methods
PHP provides a number of methods called "Magic Methods" that allow developers to work neatly in object oriented programming. Magic Methods are started or identified with two underscore (__) this are functions that executed when a certain event are met. They provide useful functionality that you can use.

Here are the Magic Methods that we will learn in this tutorial

__get()
__set()
__call()
__construct()
__destruct()
__toString()
__clone()




Constructors and Destructors

let's start with __construct() do you remember this magic method? Yes we've already used it in Part 5 of my tutorial. This is the most commonly used magic methods by php developers because it has a magic that can define a variable, call a function, initiate objects. When you make an object is created, this is the very first function that PHP will call :) do you remember the main() in java? or constructors?


<?php
class Character {

function __construct() {
echo "Object Constructed";
}
}

$test = new Character();


?>

Output :
untitled1.JPG

look at the code example above.. I've created a new object of character class and the __construct() method automatically executed


__destruct() as the name of this magic method means it has the opposite use of the __construct(), this magic method is automatically called when when the object is destroyed or finished with executing a function, I usually use this method to clean things up like sessions or some global variables or closing the database.


<?php
class Character {

function __construct() {
echo "Object Constructed";
}

function __destruct() {
echo "<br/>Object Destructed";
}
}

$test = new Character();


?>

Output :
untitled2.JPG

as you can see after running creating a new object, the function __destruct() was automatically executed because we are done using the object. You can also use the function unset() to destroy the object.

<?php
unset($test);
?>


Magic Methods for Property

This group of magic methods are used to access a property, how to easily handle if you called an undefined property. You can also use this functions to create pseudo properties. Most php developers call it PHP property overloading.

__get(). This magic function is called when the developer tries to access a variable or a property in the object that doesn't exists. This magic method contains 1 parameter which is the name of the property that you are trying to access. This can also be use to access a private property and return its value making it a read-only property.


<?php
class Character {
private $hp = 100;
private $mp = 50;

function __get($param) {
if( isset( $this->{$param} ) ) {
echo $this->{$param};
} else {
echo "Property doesn't exists";
}
}
}

$test = new Character();
$test->hp;

?>

take a look at that code above, we've created private properties so no other class can change or access them, but I have a problem and I want to read them.. the __get() magic method jump into my brain
i access the $hp property using
$test->hp;

output :
untitled3.JPG

what if I call a property that doesn't exists?
$test->asdasd;

try to run it and see what's going to happen.


you would like to change the value of a private property? or a property that is not accessible? then you can make use of __set()


<?php
class Character {
private $hp = 100;
private $mp = 50;

function __get($param) {
if( isset( $this->{$param} ) ) {
echo $this->{$param}."<br/>";
} else {
echo "Property doesn't exists";
}
}

function __set($param, $value) {
$this->{$param} = $value;
}
}

$test = new Character();
$test->hp;
$test->hp = 10000000;
$test->hp;
?>

output :
untitled4.JPG

we used our last code in the __get() method and I want to change the $hp property in the game and put so much exp into my character so I declared the magic method __set(). It is automatically called when you put a change into a property.


Method Overloading
if we have a property overloading, we also have a magic method specially created for method overloading

__call($param, $value)

This method automatically executes when you accessed a method that is not accessible or doesn't exists at all.
It has 2 parameter: the name of the method that you are calling and an array of arguments.


<?php
class Character {
private $hp = 100;
private $mp = 50;

private function talk($param) {
echo implode(", ", $param);
}

function __call($param, $value) {
if( method_exists($this, $param) ) {
$this->{$param}($value);
} else {
echo "Method doesn't exists";
}
}
}

$test = new Character();
$test->talk("hello", "there");
?>

take a look at this code.. can we access the private method talk? If you don't have the magic method __call() we can't really access a private method because of __call() we can now accessed it

output:

untitled5.JPG

Please try to call a non existing function in the code


Cloning an object
Objects by default can be passed by referencing them. So if you assign other variables in an object will not really copy the object, it will only create a new reference to the same object. In order to copy an object PHP have built a magic method that we can use for this kind of action and it's called __clone()

so you are using this

$object2 = $object1;


this won't truly copy the $object1 because if you've made new changes in that $object1, everything lost...
so how to solve it?

here's an example use of clone


<?php
class Character {
public function __clone() {
echo "1";
}
}

$test = new Character();
$test2 = clone $test;
?>

we told $test2 to copy everything including changes in $test object using the word clone
(Please correct if there is wrong with this because I'm not so sure).


Converting objects to string
what if I want to do something like

<?php
$test = new Character();
echo $test;
?>

what will happen? there will be errors correct? I want to echo the object as string. Good news, PHP has a magic method called __toString. This method is automatically called if you try to use the object as a string and this method will give us the power if what we want to do or return a string value


<?php
class Character {
function __toString() {
return "put what you want here...";
}
}

$test = new Character();
echo $test;
?>


Conclusion
We've seen the power of some magic methods that we can use to make our php programs neat and less code. This methods really help us in so many things like the construct and destruct also if want to access some not accessible properties and methods and give errors if they don't even exists.

Please try to check some more magic methods at http://php.net/manua...oop5.magic.php

have fun :)
  • 0
Life has no CTRL+Z
Never Forget To HIT "LIKE" If I Helped




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download