PHP5的OOP中的魔术方法

翻阅一些计算机中的旧的文档时,在看What’s New in PHP5时看到的,发现一些PHP5的OOP的一些很有趣的特性,主要是以下方法:

  • __toString()
  • __call()
  • __get()
  • __set()

就当是做一个记录吧

1.__toString()
把对象转换成String的方法,例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
class Person
{
    public $name;
    function __toString()
    {
        return $this->name;
    }
}
$myPerson = new Person;
$myPerson->name = 'Chris Shiflett';
echo $myPerson;
/* Chris Shiflett */
?>

2.__call()
虚拟方法,可以用来处理一个没有被(预先)定义的方法,例子:

1
2
3
4
5
6
7
8
9
10
11
<?php
class MyClass
{
    public function __call($method, $arguments)
    {
        echo "$method() does not exist.";
    }
}
$myObject = new myClass;
$myObject->asdf();
?>

3.__get()
读取虚拟属性,例子:

1
2
3
4
5
6
7
8
9
10
11
<?php
class MyClass
{
    public function __get($property)
    {
        return 'PHP';
    }
}
$myObject = new myClass;
echo $myObject->asdf;
?>

4.__set()
写入虚拟属性,例子:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
class MyClass
{
    public function __set($property, $value)
    {
        echo "$property = $value";
        /* Store in DB? */
    }
}
$myObject = new myClass;
$myObject->asdf = 'PHP';
?>

No Responses

Leave a Comment

(Necessary)

(Necessary, will not be published)

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.