dtcaw02086 2015-04-03 22: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 23: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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!