如何将get和set方法/函数指定为类';PHP中的属性?

如何将get和set方法/函数指定为类';PHP中的属性?,php,object,setter,getter,Php,Object,Setter,Getter,使用PHP,如何定义/声明getter和setter方法/函数作为类中属性声明的一部分 我试图做的是将getter和setter方法指定为属性的一部分,而不是单独声明set\u propertyName($value)和get\u propertyName()函数/方法 我得到的是: class my_entity { protected $is_new; protected $eid; // entity ID for an existing entity public

使用PHP,如何定义/声明getter和setter方法/函数作为类中属性声明的一部分

我试图做的是将getter和setter方法指定为属性的一部分,而不是单独声明
set\u propertyName($value)
get\u propertyName()
函数/方法

我得到的是:

class my_entity {
    protected $is_new;
    protected $eid; // entity ID for an existing entity
    public function __construct($is_new = FALSE, $eid = 0) {
        $this->is_new = $is_new;
        if ($eid > 0) {
            $this->set_eid($eid);
        }
    }

    // setter method
    public function set_eid($eid) {
        $is_set = FALSE;
        if (is_numeric($eid)) {
            $this->eid = intval($eid);
            $is_set = TRUE;
        }
        return $is_set;
    }
}
我想要什么(不将$this->eid作为对象):


PHP只允许每个类使用一个getter和一个setter函数,它们是
\uuu get
&
\uu set
魔术方法。这两个神奇的方法必须处理所有私有/不可访问属性的get和set请求

在2个switch语句中,还可以添加其他属性的名称

重要的是要记住,只有当变量不可访问时才会调用
\uuuu get
\uu set
,这意味着从类内部获取或设置时,您仍然必须手动调用
set\uu eid

这是针对PHP5.5的,但是,没有获得必要的2/3多数票来接受它进入核心,因此它将不会被实现(尽管已经提交了实现该更改的代码)


它完全有可能(随着大量新的PHP引擎和Hacklang的出现)在将来重新提交,特别是如果Hacklang决定实现它的话;但是目前在PHP中没有使用C#getter/setter的选项,这在PHP中是不可能的。我以前见过类似的事情(可能在PHP手册中,可能在其他地方)。据我所知,这是C#风格的setter/getter代码,而不是PHP风格的。在PHP中,u get和u set方法是可行的,请看这是针对PHP5.6的,但投票未能获得必要的2/3多数票,因此无法实施。。。。但是除了语法上的糖分,C#getter/setter给了你什么,而编写getter/setter方法却没有?我的getter和setter方法/函数需要是公共的。你回答的那些是私人的。此外,您的代码比我的(第一个块)更详细,但它基本上做相同的事情。您可以将
get_eid
set_eid
公开,它仍然可以工作。唯一需要保密的是
$this->eid
。关于详细信息,您可以随意设置代码样式,唯一需要的部分是
\uuu get
&
\uu set
,您可以直接处理其中的所有内容。
class my_entity {
    protected $is_new;
    // entity ID for an existing entity
    protected $eid {
      set: function($value) {
        $is_set = FALSE;
        if (is_numeric($value)) {
            $this->eid = intval($value);
            $is_set = TRUE;
        }
        return $is_set;

      }, // end setter

    }; 
    public function __construct($is_new = FALSE, $eid = 0) {
        $this->is_new = $is_new;
        if ($eid > 0) {
            $this->set_eid($eid);
        }
    }

    // setter method/function removed
}
private function set_eid($id)
{
    //set it...
    $this->eid = $id;
}

private function get_eid($id)
{
    //return it...
    return $this->eid;
}

public function __set($name, $value)
{
    switch($name)
    {
        case 'eid':
            $this->set_eid($value);
        break;
    }
}

public function __get($name)
{
    switch($name)
    {
        case 'eid':
            return $this->get_eid();
        break;
    }
}