__call()是什么,怎么用的?

概述

__call()是一个魔术方法,当调用一个对象中的不能用的方法的时候就回执行这个函数。有两个参数:

public mixed __call ( string $name , array $arguments )

PHP的魔术方法都是成对出现,所以和__call()成对出现的是__callStatic()方法,在静态上下文中调用一个不可用的方法时会执行这个方法。(PHP 5.3.0 版本以上)

public static mixed __callStatic ( string $name , array $arguments )
  • string $name 是要调用的方法名。
  • array $arguments 参数是一个枚举数组,包含着要传递给$name的参数。

示例

在这个示例中我们随便构建一个MethodTest类,然后当我们先实例化一个对象然后通过对象调用一个它并不包含的runTest()方法时,就会自动调用类中__call()方法。当我们调用一个这个类中并不存在的静态方法runTest()时,则会自动调用类中__callStatic()方法。

 runTest('in object context');

// PHP 5.3.0 版本以后
MethodTest::runTest('in static context');

运行结果为:

Calling object method ‘runTest’ in object context
Calling static method ‘runTest’ in static context

使用场景

根据这两个函数的意思,就直接可以知道的作用就是当调用一个对象中没有的方法的时候,还希望它做点什么而不是给我报个错,这就是其中的一个使用场景。

但是PHP是一个极具奇淫技巧的语言,而且这些魔术函数更有用的使用方式是在实现MVC框架的时候可以实现链式调用,就像ThinkPHP中经常使用的那样。

在这个示例中,我们创建了Strings类,这个类可以构建一个字符串,还包括trim()和strlen()方法。使用__call()方法,我们就可以实现$str->trim()->strlen()这样的链式操作。

str = $str;
    }
    public function __call($name, $arguement)
    {
        $ret = '';
        switch ($name)
        {
            case 'trim' :
                $new_s = trim($this->str);
                $ret = new Strings($new_s);
                break;
            case 'strlen' :
                $ret = strlen($this->str);
                break;
            default:
        }
        return $ret;
    }
}

$s = new Strings("   codeman   ");
$length = $s->trim()->strlen();
echo  "删除空格以后的长度为:" . $length;
?>

运行结果:

删除空格以后的长度为:7

阅读更多

  • 其他的魔术函数__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(),__invoke(), __set_state(), __clone() 和 __debugInfo() 。
  • implode()函数,将数组元素合成字符串。

材料下载

点击下载 密码:glgl

你可能感兴趣的:(__call()是什么,怎么用的?)