dongzhan5246 2014-03-26 08:22
浏览 90
已采纳

如何在PHP中将get和set方法/函数指定为类的属性的一部分?

Using PHP, how do I define/declare getter and setter methods/functions as part of the declaration of a property in a class?

What I'm trying to do is specify the getter and setter methods as part of a property, instead of declaring separate set_propertyName($value) and get_propertyName() functions/methods.

What I've got:

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;
    }
}

What I want (without making $this->eid an object):

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
}
  • 写回答

2条回答 默认 最新

  • doubian19900911 2014-03-26 12:03
    关注

    This was proposed for PHP 5.5, but the vote failed to get the necessary 2/3 majority required to accept it into core, so it won't be implemented (despite the code to implement that change having been submitted).

    It's entirely possible (with the plethora of new PHP engines and Hacklang currently appearing) that it will be resubmitted at a future time, especially if Hacklang decides to implement it; but for the moment the option of using C# getters/setters isn't available in PHP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上