php访问包含对象的属性

时间:2012-08-01 11:15:11

标签: php oop object scope this

我有点问题。在javascript中,可以转发范围:

var aaa = new function () {
    that = this;
    that.bbb  = 'foo';
    this.ccc = new function () {
        this.ddd = 'bar';
        this.eee = function () {
            return that.bbb+this.ddd;
        }
    }
}

aaa.ccc.eee()将返回'foobar'。 如何在PHP中做同样的效果?我有一个代码:

class bbb {
    public $ccc = 'bar';
        function __construct () {
            echo($that->aaa.$this->ccc);
        }
}
class aaa {
    public $that;
    public $aaa = 'foo';
    public $bbb;
    function __construct () {
        echo($this->aaa);
        $this->$bbb = new bbb();
        $this->$that = $this;
    }
}
$a = new aaa ();

我是否可以使用类似的东西:

$this->bbb = new bbb ($this);

class bbb {
    public $that;
    function __contruct ($parent) {
        $that = $parent
        ....
    }
}

3 个答案:

答案 0 :(得分:3)

没有什么能阻止你做与JS代码完全相同的事情,虽然这不是你每天在PHP中看到的东西:

PHP 5.3

$aaa = (object)array(
    'bbb' => 'foo',
    'ccc' => (object) array(
        'ddd' => 'bar',
        'eee' => function() use(&$aaa){ $self = $aaa->ccc; return $aaa->bbb.$self->ddd; }
    ),
);

echo call_user_func($aaa->ccc->eee);

请注意,在PHP 5.3中,不可能在闭包内使用变量$this,因此您必须从其中一个导入的变量开始到达必需的上下文(在本例中为$aaa )。

另外,请注意您无法直接调用此功能""使用$aaa-ccc->eee(),因为PHP很糟糕:$aaa->cccstdClass类型的对象,该类没有名为eee的正式成员。

我也很可爱"这里通过引用捕获$aaa,这使得能够在一行中定义整个对象图(如果需要在一个语句中没有闭包的情况下定义按值$aaa捕获,那么闭包添加了{{ 1}}在另一个)。

PHP 5.4

$aaa->ccc->eee = function() ...

在PHP 5.4中,只要你"重新绑定"就可以在闭包中使用$aaa = (object)array( 'bbb' => 'foo', 'ccc' => (object) array( 'ddd' => 'bar', 'eee' => function() use(&$aaa) { return $aaa->bbb.$this->ddd; } ), ); $aaa->ccc->eee = $aaa->ccc->eee->bindTo($aaa->ccc); echo call_user_func($aaa->ccc->eee); 。首先是$this。出于前面提到的相同原因,你无法在定义闭包的同时做到这一点:PHP糟透了。

答案 1 :(得分:1)

你在javascript中所做的与你在PHP中所做的完全不同。在javascript中,你正在做闭包,在PHP中你正在做一些非常不正确的类。

在PHP中,最接近的等价物是(虽然因为没有IIFE等而丑陋)

$tmp = function() {
    $that = new stdClass();
    $that->bbb = "foo";

    $tmp = function() use ($that) {
        $this_ = new stdClass();
        $this_->ddd = "bar";
        $this_->eee = function() use ($that, $this_) {
            return $that->bbb . $this_->ddd;
        };
        return $this_;
    };
    $that->ccc = $tmp();
    return $that;
};

$aaa = $tmp();

var_dump( call_user_func( $aaa->ccc->eee ));
//string(6) "foobar"

在php 5.4.5中测试。

答案 2 :(得分:0)

class bbb {
    function __construct ($parrent) {
        echo $parrent->ccc;
    }
}

class aaa {
    public $aaa = 'foo';
    public $bbb;
    public $ccc = 'bar';

    function __construct () {
        echo $this->aaa;
        $this->bbb = new bbb($this);
    }
}

$a = new aaa();
相关问题