PHP set static Method


 

PHP set static Method

In this current tutorial we will study about a new method called __set_static(), which is introduced in PHP 5. With the help of this method we can assign values to a new object dynamically. Examples will help to understand the concept

In this current tutorial we will study about a new method called __set_static(), which is introduced in PHP 5. With the help of this method we can assign values to a new object dynamically. Examples will help to understand the concept

_set_static()Method in PHP :

In this tutorial we will study how to assign values of an object to another object dynamically. To do this we use __set_static() method.

We need to declare a magic method called __set_static() which is declared inside the class and by using var_export() we pass a values to it and assign the values to locally declared an object and after assigning the values we return the object.

PHP Set Static Method Example:

<?php

class A

{

public $var1;

public $var2;

public static function __set_state($array)

{

$obj2=new A;

$obj2->var1=$array['var1'];

$obj2->var2=$array['var2'];

return $obj2;

}

}

$obj1=new A;

$obj1->var1=2010;

$obj1->var2="year";

eval('$obj3='.var_export($obj1,true).';');

var_dump($obj3);

?&?>

Output:strong>

object(A)#2 (2) { ["var1"]=> int(2010) ["var2"]=> string(4) "year" }

Ads