dongshenghe1833 2011-02-22 14:14
浏览 63
已采纳

PHP:使用共享方法链接的方法

Here's something that I've been thinking about for some time. I want to chain together a set of methods like in the below shown example.
The concept of method chaining is no brainer, but what I want is to make all of our animals be added through the same add method, so how should I figure out what type of animal that we're adding inside the add method?

$zoo = new Zoo;
$lion = $zoo->lion->add('Lucas the lion');
$cockatoo = $zoo->cockatoo->add('Chris the cockatoo');

class Zoo {

    function add($name) {
        //How to figure out if the animal is a Lion or an Cockatoo?
    }

}
  • 写回答

2条回答 默认 最新

  • dongshang1979 2011-02-22 14:19
    关注

    One solution to the problem would be to override __get in the Zoo class to return a 'creator' class.

    function __get($animal){
        return new Creator($this, $animal);
    }
    

    Then let the creator class call the add function in the zoo class.

    class Creator{
        public function __construct($zoo, $animal){
        ....
        }
        public function add($details){
            $zoo->add($this->_animal, $details);
        }
    }
    

    This solution is fairly ugly, and from a future developers perspective, not that clear. As pointed out in the comments, there are better ways about going this. Doing something like:

    $zoo->add('lion', 'whatever')
    

    or

    $zoo->add( new Lion('Whatever') )
    

    May be a better solution and in my opinion it is far clear to other developers what is happening. (This may not be the case for you, as I don't know the details of exactly what you are doing).

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

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码