himanshu-m/accessors

为PHP类中不可访问的成员定义getter和setter

0.0.2 2023-04-15 10:02 UTC

This package is auto-updated.

Last update: 2024-09-15 13:12:21 UTC


README

为PHP类中不可访问的成员定义getter和setter

安装

composer require himanshu-m/accessors

使用方法

在任何类中使用此特质来构建getter和/或setter,用于类的私有和受保护的属性。它还可以允许实例方法不接受任何参数就可以调用,就像使用对象的属性一样。

use Accessors;

class AccessorsTest
{
    use Accessors;

    private string $prop1;
    private string $prop2;

    function __construct(string $p1, string $p2)
    {
	$this->prop1 = $p1;
	$this->prop2 = $p2;

	$this->acccessible("prop1");
	// prop2 can also be renamed as readonlyProp for access from outside.
	$this->readonly("readonlyProp", "prop2");
    }
}

$obj = new AccessorsTest("property1", "property2");

echo $obj->prop1;
// property1
$obj->prop1 = "changed prop1";
echo $obj->readonlyProp;
// property2
$obj->readonlyProp = "cannot change prop2...";
// Exception: Property 'readonlyProp' of class AccessorsTest is not accessible