公共,私人或受保护的房产?

TJ *_*ort 2 php phpunit laravel

我正在写一个Laravel包,但我遇到了问题.该程序包调度执行以下操作的作业:

class ExampleJob
{
    protected $exampleProperty;

    function __construct($parameter)
    {
        $this->exampleProperty = $parameter;
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要测试是否使用正确的$参数调度此作业(此值是从数据库中检索的,并且根据情况,它将是不同的值).

根据文档,Laravel允许这样做:

Bus::assertDispatched(ShipOrder::class, function ($job) use ($order) {
    return $job->order->id === $order->id;
});
Run Code Online (Sandbox Code Playgroud)

但这意味着$ order属性需要公开(在我的情况下,我有:protected $ exampleProperty;).

这是一个好习惯吗?我的意思是将类属性声明为公共属性?在OOP中封装的概念怎么样?

有什么想法吗?

小智 5

使用魔术方法__get

class ExampleJob
{
    protected $exampleProperty;

    function __construct($parameter)
    {
        $this->exampleProperty = $parameter;
    }

    public function __get($name)
    {
        return $this->$name;
    }
}

$exampleJob = new ExampleJob(42);

// echoes 42
echo $exampleJob->exampleProperty;

// gives an error because $exampleProperty is protected.
$exampleJob->exampleProperty = 13;
Run Code Online (Sandbox Code Playgroud)

未找到公共属性时调用__get方法.在这种情况下,您只需返回受保护的属性$ exampleProperty.这使得属性$ exampleProperty可以作为公共属性读取,但不能从ExampleJob类外部设置.