【问题标题】:What is wrong with this PHP static Method?这个 PHP 静态方法有什么问题?
【发布时间】:2011-07-04 08:59:06
【问题描述】:

我在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

我错过了什么吗?还是我说错了?

谢谢你..

【问题讨论】:

  • 嗯,它说你在静态方法中使用$this,你是这样,但不允许。

标签: php static static-methods


【解决方案1】:

静态方法是类成员,不绑定到对象。这意味着,$this 根本不存在。您不能在静态方法中使用它。如果fetch() 也是静态的,则称其为静态

self::fetch(/* arguments */);

如果不是,getPrefixFromSubCategoyId() 也不应该是静态的,fetch() 应该是静态的(参见上面的示例),或者你需要一个对象

$tmp = new self;
$tmp->fetch(/* arguments */);

【讨论】:

  • 你不能在static function下调用non-static functionstatic方法一旦你使用你的类就会被初始化,但是not-static functions一旦你使用new关键字就会被初始化。
【解决方案2】:

$this 是对当前对象的引用。它不是对类的引用。由于您是静态使用它,因此您没有对象。您还必须在那里进行静态调用。

【讨论】:

    【解决方案3】:

    $this 用于获取实例变量或方法(简单的成员,如果您有一个使用new 定义的对象,则基本上是当前对象)但是当您想要访问静态变量时,您应该使用$self::some_varible 和@987654324 @ 是作用域解析运算符。

    如果您确实想在static function 下使用它们,则必须声明您的方法或变量static

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 2011-08-26
      • 2013-08-18
      • 2014-08-31
      相关资源
      最近更新 更多