我有这个方法,我想在其中使用 $this,但我得到的只是:致命错误:不在对象上下文中时使用 $this。
我怎样才能让它发挥作用?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
这才是正确的做法
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
对于
静态方法,使用
self::
而不是 $this->
。
请参阅:PHP 静态方法教程了解更多信息:)
不能在静态函数中使用
$this
,因为静态函数独立于任何实例化对象。
尝试使该函数不是静态的。
编辑: 根据定义,静态方法可以在没有任何实例化对象的情况下调用,因此在静态方法中使用
$this
没有任何意义。
在静态函数中只能使用 self:: 调用静态函数,如果你的类包含你想要使用的非静态函数,那么你可以声明同一个类的实例并使用它。
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
访问器
this
指的是类的当前实例。由于静态方法不会脱离实例,因此禁止使用 this
。所以这里需要直接调用该方法。静态方法不能访问实例范围内的任何内容,但可以访问实例范围之外的类范围内的所有内容。
遗憾的是 PHP 没有显示足够描述性的错误。你不能在静态函数中使用 $this-> ,而是使用 self:: 如果你必须在同一个类中调用函数
下面是一个以错误的方式调用类的方法时会发生的情况的示例。执行此代码时您会看到一些警告,但它会工作并打印:“我是 A:正在打印 B 属性”。 (在php5.6中执行)
class A {
public function aMethod() {
echo "I'm A: ";
echo "printing " . $this->property;
}
}
class B {
public $property = "B property";
public function bMethod() {
A::aMethod();
}
}
$b = new B();
$b->bMethod();
在作为静态方法调用的方法中使用的变量 $this 似乎指向“调用者”类的实例。在上面的示例中,A 类中使用了 $this->property,它指向 B 类的属性。
编辑:
当从对象上下文中调用方法时,伪变量 $this 可用。 $this 是对调用对象的引用(通常是该方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。 PHP > 基础知识
return (new static)->bar($string)
protected static function foo($string)
{
// $bar = $this->createHashFromString(string); //no
$bar = self::staticHash($string);
// ...
}
// give it a different name otherwise you're in loop.
protected static function staticHash($string): string
{
return (new static)->createHashFromString($string);
}
// this might be in a trait for a hash function you're using sitewide
// and you can access it a static function via the above function
function createHashFromString($string): string
{
return hash('xxh128', $string);
}