dtcaw02086 2015-04-03 14:52
浏览 272
已采纳

PHP - 带有静态函数的init类

I would like to call a class without initializing it even if it's normally not static. So basically it should init itself with the first method call.

I'm wondering how laravel is doing this:

$someClass = SomeClass::where()->get()

This works on every method they provide.

I googled a long time but as long as you don't know the name of this behavior it's really hard to find.

Would be nice if you could help me out.

  • 写回答

2条回答 默认 最新

  • drpiqlzrh62917192 2015-04-03 15:09
    关注

    Laravel (sometimes) calls this feature a "Facade" -- explaining how this is accomplished in Laravel means going way down the Laravel rabbit hole and is beyond the scope of a single Stack Overflow answer -- if you're interested in that I'm the author of a 10 article series that covers the implementation details of a lot of Laravel's "magic" methods -- worth checking out if you're the sort who likes those sort of nitty gritty details. The PHP manual entry on overloading is also useful.

    The short version is, all PHP classes have a magic method named __callStatic. If your class has __callStatic defined

    class Foo
    {
        public function __callStatic($method, $args)
        {
        }
    }
    

    and you call a method that does not exist, or is protected/private

    Foo::notThere(1,2,'foo');
    

    Then PHP will call the __callStatic method instead, with $method being the method's name (notThere above) and $args being an array of parameters passed to the method (1, 2, and foo above)

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部