简体   繁体   English

PHP Pipeline,为什么要克隆对象?

[英]PHP Pipeline, why is the object getting cloned?

I was looking at some php code and stumbled on a pipeline script. 我在看一些php代码,偶然发现了管道脚本。 In the method to add something to the pipeline: 在向管道添加内容的方法中:

public function pipe(callable $stage)
{
    $pipeline = clone $this;
    $pipeline->stages[] = $stage;
    return $pipeline;
}

The object is getting cloned, and returned. 该对象将被克隆并返回。 Could someone explain me the advantages of this approach, wouldn't the following code return the same results? 有人可以向我解释这种方法的优势,下面的代码不会返回相同的结果吗?

public function pipe(callable $stage)
{       
    $this->stages[] = $stage;
    return $this;
}

No, it won't return the same. 不,它不会返回相同的值。 Clone creates a copy of the object, which is sometimes the desired behaviour. Clone创建对象的副本,有时这是所需的行为。

class WithoutClone {
    public $var = 5;

    public function pipe(callable $stage)
    {       
        $this->stages[] = $stage;
        return $this;
    }
}

$obj = new WithoutClone();
$pipe = $obj->pipe(...);
$obj->var = 10;
echo $pipe->var; // Will echo 10, since $pipe and $obj are the same object 
                 // (just another variable-name, but referencing to the same instance);

// ----

class Withlone {
    public $var = 5;

    public function pipe(callable $stage)
    {       
        $pipeline = clone $this;
        $pipeline->stages[] = $stage;
        return $pipeline;
    }
}

$obj = new WithClone();
$pipe = $obj->pipe(...);
$obj->var = 10;
echo $pipe->var; // Will echo 5, since pipe is a clone (different object);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 PHP - 为什么用我克隆的对象日期时间属性更新对象日期时间属性? - PHP - Why object datetime attribut is updated with my cloned object datetime attribut? 如何取消设置克隆的 PHP 对象的 id - How to unset the id of a cloned PHP object 使用 WordPress 上的复制器插件安装克隆站点时,为什么会出现安装错误,指出“wp-config.php 为空”? - When using the duplicator plugin on WordPress to install a cloned site, why am I getting an install error stating 'wp-config.php is empty'? 如何在PHP 5.3中引用克隆对象中的父对象属性? - How to make reference to a parent object property in the cloned object in PHP 5.3? 在php上获取对象值,不知道为什么会出错 - getting object value on php , no idea why error 无法在PHP中克隆的dateinterval对象上设置属性 - Can't set properties on a cloned dateinterval object in PHP 可以克隆PHP生成器吗? - Can PHP generators be cloned? 获取php生成的json文件到jquery - 空对象 - 为什么? - getting json file generated by php to jquery - empty object - why? PHP Mongo Aggregate异常:管道元素0不是对象 - PHP Mongo Aggregate exception: pipeline element 0 is not an object 在PHP中获取对象依赖 - Getting object dependencies in PHP
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM