PHP的重载及魔术点子

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

 

5.__sleep,__wakeup
__sleep当使用serialize时被调用,当你不需要保留大目的的富有数据时很有用

 

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

?>

 

定义:PHP所提供的”重载“(overloading)是指动态地”创立”类属性和办法。(大家是透过魔术点子(magic
methods)来落实的)

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

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

?>

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

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

?>
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的换行符
    }
}
<?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";
?>

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

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

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

__isset对不可访问或不存在的性质调用isset()或empty()时被调用
__unset对不可访问或不设有的性质举办unset时被调用

 

作用:利用情势方法可以轻松实现PHP面向对象中重载(Overloading即动态创设类属性和方法)

悬停,先安利一波重载的定义及应用形式:

 

 

7.__toString
当一个类被转换成字符串时被调用

定义:PHP 将持有以
__(两个下划线)伊始的类情势保存为魔术点子。所以在定义类方法时,除了上述魔术点子,提出并非以
__ 为前缀。

先是你要精晓哪些是php的魔术点子,它不是变魔术的,倘诺你想学学变魔术来错地点了啊!

1.__construct,__destruct
__constuct构建对象的时被调用;
__destruct明确销毁对象或脚本停止时被调用;

看完了吧?好赏心悦目!

__set当给不可访问或不设有属性赋值时被调用
__PHP,get读取不可访问或不设有属性时被调用

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

6.__clone
进展对象clone时被调用,用来调整目的的仿造行为

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

 

骨子里过多博客主已经写过这一个措施了、、、然而我或者要说五次。。什么人让你来听了啊,码这么多字也不容易看完再走呢!

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

作者原创、转载请阐明出处

相关文章