<?php
declare(strict_types=1);//开启强类型模式
//不可访问的方法:private/protected/不存在的方法
class Person{
public function say(){
echo "Hello world";
echo "\r\n";
}
}
(new Person())->say();//调用类中存在的方法
(new Person())->eat('food');//调用类中不可访问的方法
调用类中不存在的方法
PHP Fatal error: Uncaught Error: Call to undefined method Person::eat() in /home/zrj/www/zhangrenjie_test/test/36.php:26
Stack trace:
#0 {main}
thrown in /home/zrj/www/zhangrenjie_test/test/36.php on line 26
class Person
{
public function say()
{
echo "Hello world";
echo "\r\n";
}
// 在对象中调用一个不可访问方法时,__call() 会被调用。
public function __call($functionName, $arguments)
{
echo "您调用了类中不存在的方法:" . $functionName . "\r\n";
echo "接受的参数为:" . print_r($arguments, true);
}
}
(new Person())->say();
(new Person())->eat('food', 'chicken', 'bull');
Hello world
您调用了类中不存在的方法:eat
接受的参数为:Array
(
[0] => food
[1] => cocal
[2] => bull
)
class Person
{
public function __call(string $name, array $arguments)
{
echo "Call not exists dynamic method :" . $name . "\r\n";
echo $name . " : " . $arguments[0] . "\r\n\r\n";
}
/** PHP 5.3.0之后版本 */
public static function __callStatic(string $name, array $arguments)
{
echo "Call not exists static method :" . $name . "\r\n";
echo $name . " : " . $arguments[0] . "\r\n\r\n";
}
}
(new Person())->say('hello world');
(new Person())->__call('say', ['hello world']);
Person::do('coding php');
Person::__callStatic('do', ['coding java']);
Call not exists dynamic method :say
say : hello world
Call not exists dynamic method :say
say : hello world
Call not exists static method :do
do : coding php
Call not exists static method :do
do : coding java