Jom*_*Jom 66 php oop static-methods this
我有这个方法,我想使用$ this,但我得到的是:致命错误:当不在对象上下文中时使用$ this.
我怎样才能让它发挥作用?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
Run Code Online (Sandbox Code Playgroud)
Sar*_*raz 120
这是正确的方法
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
Run Code Online (Sandbox Code Playgroud)
使用self::,而不是$this->用于静态方法.
请参阅:PHP静态方法教程以获取更多信息:)
cat*_*try 14
您不能$this在静态函数中使用,因为静态函数独立于任何实例化对象.尝试使该功能不是静态的.
编辑:根据定义,可以在没有任何实例化对象的情况下调用静态方法,因此$this静态方法内部没有有意义的使用.
小智 5
只能使用 self:: 在静态函数中调用静态函数,如果您的类包含要使用的非静态函数,那么您可以声明同一个类的实例并使用它。
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55248 次 |
| 最近记录: |