对象类型

如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,将会创建一个内置类 stdClass 的实例。如果该值为 NULL ,则新的实例为空。数组转换成对象将使键名成为属性名并具有相对应的值。对于任何其它的值,名为 scalar 的成员变量将包含该值。

$obj  = (object)  'ciao' ;

echo   $obj -> scalar ;   // ciao     其他值

  $object = (object) ['propertyOne' => 'foo','propertyTwo' => 42,];  

echo $object->propertyOne    //foo   数组

//我不懂的例子

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).

        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.

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");

$obj->setAdresse("Boston");

$obj->getInfo();

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,143评论 0 13
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,735评论 0 38
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 7,593评论 0 3
  • 把当前目录作为Root Document只需要这条命令即可:php -S localhost:3300 也可以指定...
    绚烂的时光阅读 4,032评论 0 1
  • By 思瑶-给我起这个标题的混蛋请站出来……你说得对! 这期的主题估计催的紧,隔着手机屏幕都能感受到远在非洲学霸的...
    叽咕JIGU阅读 3,599评论 0 0