这个 PHP 静态方法有什么问题?
我已经在类 category
中声明了一个静态方法,
public static function getPrefixFromSubCategoyId($subCategoryId) {
$prefix = $this->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
return $prefix[0]['prefix'];
}
我确信我使用了正确的代码段,因为当我在类范围之外使用相同的代码和以下代码时,它可以正常工作,
$category = new Category($dbh);
$subCategoryId = 6;
$prefix = $category->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
echo $prefix[0]['prefix'];
但是当我初始化静态方法时具有以下语法的方法。
$prefix = Category::getPrefixFromSubCategoyId(4);
它给了我以下错误。
Fatal error: Using $this when not in object context
我错过了什么吗?或者我以错误的方式声明它?
谢谢..
I have declared a static method in class category
public static function getPrefixFromSubCategoyId($subCategoryId) {
$prefix = $this->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
return $prefix[0]['prefix'];
}
i am sure that i am using correct piece of code because when i use the same code outside the class scope with following code it works properly
$category = new Category($dbh);
$subCategoryId = 6;
$prefix = $category->fetch(array('table' => 'subCategories', 'id' => $subCategoryId));
echo $prefix[0]['prefix'];
but when i initialize the static method with following syntax.
$prefix = Category::getPrefixFromSubCategoyId(4);
it gives me following error.
Fatal error: Using $this when not in object context
am i missing something? or am i declaring it the wrong way?
thank you..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
静态方法是类成员,不绑定到对象。这意味着
$this
根本不存在。您不能在静态方法中使用它。如果fetch()
也是静态的,则称其为静态如果不是,则
getPrefixFromSubCategoyId()
也不应该是静态的,fetch()
应该是静态的(参见上面的示例),或者您需要一个对象static methods are class members and aren't bound to an object. This means, that
$this
simply doesn't exists. You cannot use it in static methods. Iffetch()
is static too, call it staticIf not either
getPrefixFromSubCategoyId()
should not be static too,fetch()
should be static (see example above), or you need an object$this 是对当前对象的引用。它不是对类的引用。由于您静态地使用它,因此没有对象。您还必须在那里进行静态调用。
$this is a reference to the current object. It is not the reference to the class. Since you are using it statically you have no object. You would have to make a static call in there as well.
$this
用于获取实例变量或方法(简单成员,如果您使用new
定义的话,则基本上是当前对象),但是当您想要访问静态变量时,您需要应该使用$self::some_varible
和::
是范围解析运算符。如果您确实想在
静态函数
下使用您的方法或变量,则必须将它们声明为static
。$this
is used to get instance variables or methods (simple members and basically the current object if you have one defining withnew
) but when you want to reach the static variables you should use$self::some_varible
and::
is scope resolution operator.You must declare your methods or variables
static
if you do want to use them under astatic function
.