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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀