【问题标题】:PHP, execute public static function from $classPHP,从 $class 执行公共静态函数
【发布时间】:2017-04-27 04:33:28
【问题描述】:

如何在 php.ini 中从不同的命名空间调用类的公共静态函数。我有这个代码:

namespace x\y\z;

use x\y\z\h\Foo;
...
$classinstring = 'Foo';
$classinstring::getType();

我得到错误,php 找不到类 Foo Fatal error: Uncaught Error: Class 'Foo' not found 我该怎么做?

【问题讨论】:

    标签: php php-7


    【解决方案1】:

    要实例化一个类,你应该使用new

    $classinstring = new Foo();

    编写$classinstring = 'Foo' 分配$classinstring 字符串文字"Foo"


    命名空间是您的类的快捷方式。这两个语句是相等的:

    namespace x\y\z;
    
    use x\y\z\h\Foo;
    
    $bar = new Foo();
    

    $bar = new \x\y\z\h\Foo();
    


    还要确保你的类名拼写与文件名完全相同。


    静态方法不需要实例化即可使用;您可以直接从类名中调用它们。

    Foo::someCustomMethod();

    您以getType() 为例,虽然这是一个原生PHP 全局函数并且不能作为静态方法调用,除非您在类中定义了自己的getType() 方法.

    class Foo
    {
        public function getType()
        {
            echo 'This is my own function.';
        }
    
        public static function callAnywhere()
        {
            echo 'You don't have to make a new one to use one.';
        }
    }
    

    如果您需要调用类方法,这很好。

    Foo::callAnywhere() // prints 'You don't have to make a new one to use one.';
    
    $bar = new Foo();
    $bar->getType(); // prints 'This is my own function.'
    
    $other = new stdClass();
    echo getType($other); // prints 'object';
    

    【讨论】:

      【解决方案2】:

      试试这个。

      namespace x\y\z;
      
      use x\y\z\h\Foo;
      ...
      $classinstring = 'Foo';
      $classinstring = new $classinstring;
      $classinstring::getType();
      

      也许您的文件无法找到和访问类 x\y\z\h\Foo。确保您的类 Foo 具有 namespace \x\y\z\h 的命名空间。

      【讨论】:

        猜你喜欢
        • 2019-10-02
        • 2014-12-28
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 2013-05-13
        • 2010-10-19
        相关资源
        最近更新 更多