PHP 5 Tutorial - __set() Magic Method

This tutorial will guide you through the __set() Magic Method. The __set() Magic method in PHP5 gets called when setting the value to an undeclared or undefined attributes of an class. With this method the programmer can keep track on the variables which are not defined inside the class.





Syntax:

< ?
function __set($data,$value)
{
	//$data - holds the name of the undefined attributes
        //$value - holds the value assigned to the undefined attributes.
}
?>

Example: __set Magic Method Call

< ?
class magicmethod
{
	function __set($data,$value)
	{
		echo "Error assigning values to undefined attributes";
		echo "attributes Called:".$data;
		echo "Value assigned to attributes:".$value;
	}
 
}
$a = new magicmethod();
$a->setData = 20;
?>

Output:
Error assigning values to undefined attributes
attributes Called:setData
Value assigned to attributes:20

Explanation for the Example:

Here i am trying to assigned value 20 to an attribute setData of magicmethod class.

In the magicmethod class setData is not defined so the php compiler excutes __set() magic method and displays error message.

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)