>  기사  >  백엔드 개발  >  PHP는 매우 흥미로운 코드를 구현합니다(확장 가능).

PHP는 매우 흥미로운 코드를 구현합니다(확장 가능).

WBOY
WBOY원래의
2016-08-08 09:23:241227검색

이전 클라우드 노트를 보다가 아주 흥미로운 노트를 발견했습니다. 아래는 멤버 함수와 멤버 변수를 동적으로 추가할 수 있는 PHP 프로그램입니다. 예전에 PHP 매뉴얼에서 본 적이 있는데, 매우 흥미롭다고 생각해서 공유하고 싶습니다.

//整个类同过闭包以及魔法方法动态的添加了一系列的全局变量以及函数,在编程过程中对扩展一个方法是非常有用的
//构造方法中表示在构造的时候可以传入一个数组,同事数组的键值为属性名,值为属性值
//__call方法表示对没有的方法时调用此方法
<?php
//定义一个类
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                $this->{$property} = $argument;
            }
        }
    }

//魔法方法,当没有调用的函数是回调此方法
    public function __call($method, $arguments) {
    //将对象本身作为参数的第一个值合并到参数中
        $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
//判断是否存在调用的模块,如果存在判断是否可以调用,如果可以调用,将模块(函数)名,和参数通过call_user_func_array()去执行函数
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

// Usage.

$obj = new stdObject();
//定义类中的全局变量
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;
//定义的一个闭包函数
$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
    echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};

$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
    $stdObject->age = $age;
};
//调用闭包函数
$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.

// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
//循环取出对象中的函数/变量名,分别动态生成对应的set和get函数
foreach ($obj as $func_name => $value) {
    if (!$value instanceOf Closure) {

        $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables.
            $stdObject->{$func_name} = $value;
        };

        $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables.
            return $stdObject->{$func_name};
        };

    }
}
//调用函数
$obj->setName("John"); //会首先调用__call函数,之后会回调到闭包函数定义的地方
$obj->setAdresse("Boston");

$obj->getInfo();
?> 

위 내용은 몇 가지 측면을 포함하여 PHP로 구현된 매우 흥미로운 코드(확장 가능)를 소개합니다. 이것이 PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.