簡體   English   中英

PHP,從$ class執行公共靜態函數

[英]PHP, execute public static function from $class

如何在php中從不同的命名空間調用類的公共靜態函數。 我有這個代碼:

namespace x\y\z;

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

我得到錯誤,PHP無法找到類Foo Fatal error: Uncaught Error: Class 'Foo' not found我怎么能這樣做?

要實例化一個類,您應該使用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';

嘗試這個。

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的命名空間

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM