php - __callStatic() : instantiating objects from static context?

标签 php static instantiation magic-methods

我对 PHP 中的“静态”和“动态”函数和对象如何协同工作感到困惑,特别是在 __callStatic() 方面。

How __callStatic() works:

You can have a normal class MyClass, where within the class you can put a static function called __callStatic(), which gets called only when MyClass doesn't have a static function by the name you want.

i.e. I call MyClass::newFunction();

newFunction() is called statically but MyClass does not have it declared. So, then __callStatic() gets called and inside you can say

$myObject=new SomeOtherClass();
$myObject->newFunction();

which calls the function you wanted but on some other object.

简短版本:

换句话说,__callStatic() 执行以下操作:

MyClass::newFunction();

它隐藏了这个:

(new SomeOtherClass())->newFunction();

现在说什么?看起来像是从类中调用静态函数的代码,结果是从其他类中调用该函数并通过实例化而不是静态地调用它。

请解释一下!

为什么这样做?你能在其他地方做类似的事情吗,比如 C++ 或 Java?我正在寻找关于语言中静态和动态函数的简短但信息丰富的解释,以及在这种情况下 __callStatic() 违反还是符合语言的大局结构体。或者它完全是一种新的语言构造。

最佳答案

__callStatic() 为开发人员提供了对 static 方法调用使用react的可能性,即使该方法不存在不可访问来自类外部(受保护)。这对于动态、通用代码生成很有用。

<小时/>

示例:您有此类:

class Test {

    protected static function myProtected($test) {
        var_dump(__METHOD__, $test);
    }

    public static function __callStatic($method, $args) {
        switch($method) {
            case 'foo' :
                echo 'You have called foo()';
                var_dump($args);
                break;

            case 'helloWorld':
                echo 'Hello ' . $args[0];
                break;

            case 'myProtected':
                return call_user_func_array(
                    array(get_called_class(), 'myProtected'),
                    $args
                );
                break;                      
        }

    }

}

尝试调用:

// these ones does not *really* exist
Test::foo('bar');
Test::helloWorld('hek2mgl');

// this one wouldn't be accessible
Test::myProtected('foo');

关于php - __callStatic() : instantiating objects from static context?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840911/

相关文章:

c# - 将静态列表分配给非静态列表

java - java中static指的是什么

Android Viewpager 保存数据和 View

c# - 类的实例不存在?

PHP 等同于 Perl 的 'use strict'(要求变量在使用前进行初始化)

php - Tumblr API 从 HTML Canvas 发布照片

php - isset 静态类属性

php - phpdoc的多个子包

php - 将所有图像从 mysql 数据库 blob 提取到目录

c++ - c++中非void return函数模板的显式方法