PHP常用魔术方法(__call魔术方法:)

2023-05-22,,

魔术方法  __call

<?php
//文件名:index.php
define('a',__DIR__);
include '/IMooc/Loader.php';
spl_autoload_register('\\IMooc\\Loader::autoload'); $Object = new \IMooc\Object(); echo $Object->test("哎哟喂",123);//在调用test不存在的方法时,会自动调用__call方法
/*输出:
string(4) "test"
array(2) {
[0]=>string(9) "哎哟喂"
[1]=>int(123)
}
试一试
*/
<?php
//文件名:Object.php

namespace IMooc;
class Object
{ function __call($name, $arguments)//$name方法名=test,$arguments参数="哎哟喂",123
{
var_dump($name,$arguments);
return "试一试";
}
}

静态魔术方法__callStatic


<?php
//文件名:index.php
define('a',__DIR__);
include '/IMooc/Loader.php';
spl_autoload_register('\\IMooc\\Loader::autoload'); $Object = new \IMooc\Object();
echo IMooc\Object::test("hello1",1234);
/*输出:
string(4) "test"
array(2) {
[0]=>string(6) "hello1"
[1]=>int(1234)
}
试一试
*/
 
<?php
namespace IMooc;//文件名:Object.php
class Object
{
//静态方法
static function __callStatic($name, $arguments)//$name静态方法名=test,$arguments参数数组="哎哟喂",123
{
var_dump($name,$arguments);
return "试一试";
}
}

PHP常用魔术方法(__call魔术方法:)的相关教程结束。

《PHP常用魔术方法(__call魔术方法:).doc》

下载本文的Word格式文档,以方便收藏与打印。