Ibr*_*mar 0 php static static-methods
我在课堂上声明了一个静态方法 category
public static function getPrefixFromSubCategoyId($subCategoryId) {
$prefix = $this->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
return $prefix[0]['prefix'];
}
Run Code Online (Sandbox Code Playgroud)
我确信我正在使用正确的代码片段,因为当我在类范围之外使用相同的代码并使用以下代码时,它可以正常工作
$category = new Category($dbh);
$subCategoryId = 6;
$prefix = $category->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
echo $prefix[0]['prefix'];
Run Code Online (Sandbox Code Playgroud)
但是当我使用以下语法初始化静态方法时.
$prefix = Category::getPrefixFromSubCategoyId(4);
Run Code Online (Sandbox Code Playgroud)
它给了我以下错误.
Fatal error: Using $this when not in object context
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?或者我是以错误的方式宣布它?
谢谢..
静态方法是类成员,不绑定到对象.这意味着,$this根本就不存在.您不能在静态方法中使用它.如果fetch()也是静态的,请将其称为静态
self::fetch(/* arguments */);
Run Code Online (Sandbox Code Playgroud)
如果不是也不getPrefixFromSubCategoyId()应该是静态的,那么fetch()应该是静态的(参见上面的例子),或者你需要一个对象
$tmp = new self;
$tmp->fetch(/* arguments */);
Run Code Online (Sandbox Code Playgroud)