【问题标题】:How to access Class Object in Closure Object?如何访问闭包对象中的类对象?
【发布时间】:2021-08-03 12:27:53
【问题描述】:
<?php

class TryClass
{
    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function closure(Closure $callback)
    {
        return $callback(function () {});
    }
}

$try = new TryClass('polat');

$try->closure(function ($reference) {
    print_r($reference);

    // not work
    // $reference->this->data
    // $reference::this->data
    // $reference::$this->data
    // $reference->{'this'}->data
});

print_r() 响应;

Closure Object
(
    [this] => TryClass Object
        (
            [data:TryClass:private] => polats
        )

)

如何访问闭包对象中的 TryClass 对象或如何访问闭包对象中的静态对象?请帮忙,非常感谢。

通过在类中发送闭包函数,我还想在该函数中访问该类的 $this。

【问题讨论】:

    标签: php


    【解决方案1】:

    您正在将一个函数传递给您的闭包,这是您真正想要的吗?所以你的闭包调用一个函数?相反,我认为您只想将 $this 传递回您的闭包以获取它:

    class TryClass
    {
        public function closure(Closure $callback)
        {
            return $callback($this);
        }
    }
    
    (new TryClass())
        ->closure(
            function ($reference) {
                print_r($reference);
            }
        );
    

    输出是:

    TryClass Object
    (
    )
    

    在这里演示:https://3v4l.org/7Efpr

    不能做的是在不经过反射的情况下访问私有变量,这会破坏封装。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      相关资源
      最近更新 更多