dongmi1995 2016-06-16 00:24
浏览 17

通过引用传递或不传递链接到其他实例

At the moment I am working on a parser, comprised of a Document class that takes input and determines a number of processing steps to be taken. The logic of each step is dynamic to various circumstances, so is handed off to a Processor class which is passed to the Document at construction.

The goal is that my use of it will eventually look something like:

$document = new Document($input, Processors\XYZ::class);
$document->parse();
$document->output();

Document->__construct() also creates and stores in a property a new instance of the passed processor class. This leads to the part I am unsure of: The Processor instance also needs a link back to the Document. I am not sure whether I should be passing that by reference or not. I haven't found anything about this particular use of references - http://php.net/manual/en/language.references.pass.php is only really talking about functions, nothing to do with classes or instances.

I threw together this minimal test:

class base {
    //function __construct($maker) {
    function __construct(&$maker) {
        if (!is_a($maker, makeSay::class, true)) { echo 'oh no!<br/>';}
        $this->maker = $maker;
    }
    function say() {echo 'Base, made by ' . $this->maker->name;}    
}

class child extends base {
    function say() {echo 'Child, made by ' . $this->maker->name;}
}

class makeSay {
    public $name = 'default';
    function __construct($thing, $name) {
        if (!is_a($thing, base::class, true)) { echo 'oh no!<br/>';}
        $this->thing = new $thing($this);
        $this->name = $name;
    }

    function say() {$this->thing->say();}
}

$a = new makeSay(child::class, 'This Guy');

$a->say();

... which has similar logic to the constructors in my real script, but it seems as though there is no difference in execution whether base->__construct() looks like function __construct(&$maker) or function __construct($maker).

Is there any difference to be expected between the two?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
    • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥120 计算机网络的新校区组网设计
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据