【问题标题】:Using $this when not in object context static function不在对象上下文静态函数中时使用 $this
【发布时间】:2013-05-01 18:58:58
【问题描述】:

这是我生成随机字符串的静态函数:

    public static function generateCode($salt)
    {
        $this->generate = substr(hash('sha512', $salt), 0, 15);
        return $this->generate;
    }

我就是这样使用它的:

            $this->insert->execute(array(
            ":username" => $username,
            "generated_code" => self::generateCode($email)
            ));

我已经声明了财产:

    protected $generate;

收到此错误:

Fatal error: Using $this when not in object context in C:\xampp\htdocs\drip\class\users.class.php on line 154

第 154 行:

        $this->generate = substr(hash('sha512', $salt), 0, 15);

这是怎么回事?为什么它给我这个错误?

【问题讨论】:

  • $this 在静态函数中不存在。它们只存在于类上下文中,没有对象实例

标签: php


【解决方案1】:

静态方法不属于对象的实例,$this与实例有关...

在这种情况下,我认为除了简单地返回哈希结果(可能是 lambda 表达式的候选者?)之外,您不需要任何其他东西

public static function generateCode($salt)
{
    return substr(hash('sha512', $salt), 0, 15);
}

【讨论】:

  • 哦,我现在明白了...非常感谢。
  • @user2326532 当然可以,为什么不呢?
  • @user2326532 方法的访问级别与它是类还是实例级别是分开的。
【解决方案2】:

static 函数意味着它“绑定”到类,而不是每个实例(对象)。像这样称呼它:

  ClassName::generateCode($email);

此外,您不能在静态函数中使用对象成员。让您的$generate 成员也成为static,并将其称为:

  ClassName::$generate 

【讨论】:

  • 它在同一个类中,因此我称它为 self::,我读过你必须使用 self:: 如果它在同一个类中,但是,它没有修复错误。
  • 那是成员是静态的,而不是方法。
  • 访问内部类(静态)方法时可以使用self::static::,没错。
  • @Orbling 是的,但你不能在非静态成员上使用 self::static::
  • @BartFriederichs:是的,只有静态方法和属性。将这两个视为 $this 的类级别版本会很有帮助。
【解决方案3】:

在你的函数中你应该使用 self 而不是 $this 因为函数被声明为静态的。

将您的成员 $generate 声明为静态,否则它将不起作用。

【讨论】:

    猜你喜欢
    • 2022-12-03
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多