dongtangze6393 2014-01-31 14:18
浏览 28
已采纳

检查setter是否设置为PHP

Hi is there a way to check if the setter in a class is set?

I've tried is_object and isset but without a proper result.

Example:

class FruitsModel{

    public $fruitId;

    public function setFruitId($fruitId){
        $this->fruitId = $fruitId;
    }

    public function displayFruit()
    {
        if(SETTER_FRUIT IS NOT SET){throw new Exception("FruitId is missing!");}

        echo $this->fruitId;

    }

}
  • 写回答

5条回答 默认 最新

  • douzhi8244 2014-01-31 14:39
    关注

    A developer should know which methods need to be implemented in the class. Assuming that he does not, how could we force him to implement them without checking the existance of certain methods in your other methods programatically?

    That's where interfaces come in handy and what they are for. See an interface as a contract that defines which methods a class must implement.

    So the cleanest way to tackle your task would be to just implement an interface.

    FruitsModelInterface.php

    <?php
    
    interface FruitsModelInterface{
    
        public function setFruitId($fruitId);
    
    }
    

    FruitsModel.php

    <?php
    
    class FruitsModel implements FruitsModelInterface{
    
        protected $fruitId;
    
        public function setFruitId($fruitId){
            $this->fruitId = $fruitId;
        }
    
        public function displayFruit()
        {
            if(is_null($this->fruitId))
                throw new FruitsModelException('Fruit ID missing!');
            echo $this->fruitId;
            // You'd probably better go with calling the Method
            // getFruit() though and return $this->fruitId instead of echoing
            // it. It's not the job ob the FruitsModel to output something
        }
    
    }
    

    Really, that's all the magic. Just force the FruitsModelInterface to implement the setFruitId() method by implementing the proper interface. In your displayFruit() you just check if the property really has been assigned.

    I also made your property protected, so that you can be sure the value will just be set from within the class or it's children.

    Happy Coding!


    Further reading

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。