Home >php教程 >php手册 >PHP5试用(二)

PHP5试用(二)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-22 17:20:561326browse

抽象类

抽象类不能被实例化。

抽象类与其它类一样,允许定义变量及方法。

抽象类同样可以定义一个抽象的方法,抽象类的方法不会被执行,不过将有可能会在其派生类中执行。

例六:抽象类

<?php
abstract class foo {
    protected $x;
    abstract function display();
    function setX($x) {
        $this->x = $x;
    }
}
class foo2 extends foo {
    function display() {
        // Code
        
    }
}
?>

__call

PHP5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在的方法,__call 方法将会被自动调用。

例七:__call

<?php
class foo {
    function __call($name, $arguments) {
        print ("Did you call me? I&#39;m $name!");
    }
}
$x = new foo();
$x->doStuff();
$x->fancy_stuff();
?>

这个特殊的方法可以被用来实现“过载(overloading)”的动作,这样你就可以检查你的参数并且通过调用一个私有的方法来传递参数。

例八:使用 __call 实现“过载”动作

<?php
class Magic {
    function __call($name, $arguments) {
        if ($name == &#39;foo&#39;) {
            if (is_int($arguments[0])) $this->foo_for_int($arguments[0]);
            if (is_string($arguments[0])) $this->foo_for_string($arguments[0]);
        }
    }
    private function foo_for_int($x) {
        print ("oh an int!");
    }
    private function foo_for_string($x) {
        print ("oh a string!");
    }
}
$x = new Magic();
$x->foo(3);
$x->foo("3");
?>

__set 和 __get

这是一个很棒的方法,__set 和 __get 方法可以用来捕获一个对象中不存在的变量和方法。

例九: __set 和 __get

<?php
class foo {
    function __set($name, $val) {
        print ("Hello, you tried to put $val in $name");
    }
    function __get($name) {
        print ("Hey you asked for $name");
    }
}
$x = new foo();
$x->bar = 3;
print ($x->winky_winky);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn