因此在定义类方法时,除了上述魔术点子

看完了呢?好赏心悦目!

PHP的重载及魔术点子,PHP重载魔术点子

第三你要知道哪些是php的魔术点子,它不是变魔术的,倘若您想上学变魔术来错地点了啊!

定义:PHP 将持有以
__(七个下划线)起初的类措施保存为魔术点子。所以在定义类方法时,除了上述魔术点子,提议并非以
__ 为前缀。

作用:利用格局方法能够轻松达成PHP面向对象中重载(Overloading即动态创立类属性和章程)

骨子里过多博客主已经写过这个措施了、、、然则本身要么要说一回。。何人让您来听了呢,码这么多字也不简单看完再走啊!

1.__construct,__destruct
__constuct营造对象的时被调用;
__destruct鲜明销毁对象或脚本结束时被调用;

class Foo {

    private $name;
    private $link;

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

    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;//PHP_EOL代表php的换行符
    }
}

 

悬停,先安利1波重载的定义及运用格局:

公海赌船710,定义:PHP所提供的”重载“(overloading)是指动态地”创设”类属性和措施。(我们是因而魔术点子(magic
methods)来兑现的)

作用:当调用当前条件下未定义或不可知的类属性或艺术时,重载方法会被调用。前边将运用”不可访问属性(inaccessible properties)”和”不可访问方法(inaccessible
methods)”来称呼那几个未定义或不可知的类属性或情势。

注意:全体的重载方法都不可能不被声称为 public

 

2.__get、__set、__isset、__unset、__call、__callStatic
 //为何放1块吗?

__set当给不可访问或不存在属性赋值时被调用
__get读取不可访问或不设有属性时被调用

__isset对不可访问或不设有的质量调用isset()或empty()时被调用
__unset对不可访问或不设有的质量进行unset时被调用

__call调用不可访问或不设有的方法时被调用
__callStatic调用不可访问或不设有的静态方法时被调用

 

Example #1
使用 __get(),__set(),__isset() 和 __unset() 实行质量重载

<?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;
    }



    /**  PHP 5.1.0之后版本 */
    public function __isset($name) 
    {
        echo "Is '$name' set?\n";
        return isset($this->data[$name]);
    }

    /**  PHP 5.1.0之后版本 */
    public function __unset($name) 
    {
        echo "Unsetting '$name'\n";
        unset($this->data[$name]);
    }

    /**  非魔术方法  */
    public function getHidden() 
    {
        return $this->hidden;
    }
}


echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

看完了吗?好雅观!

5.__sleep,__wakeup
__sleep当使用serialize时被调用,当您不必要保留大指标的拥有数据时很有用

__wakeup当使用unserialize时被调用,可用来做些对象的伊始化操作

<?php
class Connection 
{
    protected $link;
    private $server, $username, $password, $db;

    public function __construct($server, $username, $password, $db)
    {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }

    private function connect()
    {
        $this->link = mysql_connect($this->server, $this->username, $this->password);
        mysql_select_db($this->db, $this->link);
    }

    public function __sleep()
    {
        return array('server', 'username', 'password', 'db');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}
?>

 

6.__clone
举办对象clone时被调用,用来调整指标的仿造行为

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {

        // 强制复制一份this->object, 否则仍然指向同一个对象
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

 

7.__toString
当1个类被转换来字符串时被调用

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {

        // 强制复制一份this->object, 否则仍然指向同一个对象
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

 

8.__set_state
当调用var_export()导出类时,此静态方法被调用。用__set_state的再次来到值做为var_export的再次回到值。

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

 

enmmm,笔者领悟你记不住的。。这么多什么人记得住啊,好烦啊、、、别,那还没讲完呢,越多情势请参考PHP的法定文书档案:http://php.net/manual/zh/,别打我,你自己去看吧,毕竟好东西还是要众乐乐的!了;另外这些代码你最好再编译器中运行一边,不然看完你估计和没看一个样2333
····  

小编原创、转发请注解出处

http://www.bkjia.com/PHPjc/1231549.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1231549.htmlTechArticlePHP的重载及魔术方法,PHP重载魔术方法
首先你要精通什么样是php的魔术点子,它不是变魔术的,假使您想深造变魔术来错地点了哦!
定义 :…

6.__clone
展开对象clone时被调用,用来调动指标的克隆行为

<?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;
    }



    /**  PHP 5.1.0之后版本 */
    public function __isset($name) 
    {
        echo "Is '$name' set?\n";
        return isset($this->data[$name]);
    }

    /**  PHP 5.1.0之后版本 */
    public function __unset($name) 
    {
        echo "Unsetting '$name'\n";
        unset($this->data[$name]);
    }

    /**  非魔术方法  */
    public function getHidden() 
    {
        return $this->hidden;
    }
}


echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

 

 

__call调用不可访问或不存在的主意时被调用
__callStatic调用不可访问或不存在的静态方法时被调用

 

<?php
class Connection 
{
    protected $link;
    private $server, $username, $password, $db;

    public function __construct($server, $username, $password, $db)
    {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }

    private function connect()
    {
        $this->link = mysql_connect($this->server, $this->username, $this->password);
        mysql_select_db($this->db, $this->link);
    }

    public function __sleep()
    {
        return array('server', 'username', 'password', 'db');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}
?>

定义:PHP所提供的”重载“(overloading)是指动态地”成立”类属性和艺术。(大家是经过魔术点子(magic
methods)来达成的)

 

7.__toString
当多个类被转换来字符串时被调用

率先你要理解什么样是php的魔术点子,它不是变魔术的,假如您想学习变魔术来错地方了啊!

2.__get、__set、__isset、__unset、__call、__callStatic
 //为什么放1块吗?

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

停下,先安利1波重载的概念及利用格局:

 

事实上过多博客主已经写过这一个形式了、、、然则小编要么要说二回。。什么人让你来听了吧,码这么多字也不不难看完再走吗!

class Foo {

    private $name;
    private $link;

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

    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;//PHP_EOL代表php的换行符
    }
}

__wakeup当使用unserialize时被调用,可用于做些对象的初阶化操作

小编原创、转发请注脚出处

定义:PHP 将有着以
__(四个下划线)开首的类格局保存为魔术点子。所以在定义类方法时,除了上述魔术点子,提议不用以
__ 为前缀。

1.__construct,__destruct
__constuct营造对象的时被调用;
__destruct分明销毁对象或脚本截至时被调用;

注意:全数的重载方法都必须被声称为 public

Example #1
使用 __get()__set()__isset() 和 __unset() 实行性能重载

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {

        // 强制复制一份this->object, 否则仍然指向同一个对象
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

 

8.__set_state
当调用var_export()导出类时,此静态方法被调用。用__set_state的重返值做为var_export的重返值。

 

作用:当调用当前条件下未定义或不可见的类属性或措施时,重载方法会被调用。前边将运用”不可访问属性(inaccessible properties)”和”不可访问方法(inaccessible
methods)”来称呼那几个未定义或不可知的类属性或措施。

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {

        // 强制复制一份this->object, 否则仍然指向同一个对象
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

__set当给不可访问或不设有属性赋值时被调用
__get读取不可访问或不存在属性时被调用

enmmm,作者掌握您记不住的。。这么多何人记得住啊,好烦啊、、、别,那还没讲完呢,更多格局请参见PHP的法定文书档案:http://php.net/manual/zh/,别打我,你自己去看吧,毕竟好东西还是要众乐乐的!了;另外这些代码你最好再编译器中运行一边,不然看完你估计和没看一个样2333
····  

5.__sleep,__wakeup
__sleep当使用serialize时被调用,当你不要求保留大指标的有着数据时很有用

__isset对不可访问或不存在的质量调用isset()或empty()时被调用
__unset对不可访问或不存在的属性进行unset时被调用

作用:利用形式方法能够轻松达成PHP面向对象中重载(Overloading即动态创立类属性和格局)

相关文章