1

This is my static function to generate a random string:

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

And that's how I use it:

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

I have declared the property:

    protected $generate;

Getting this error:

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

Line 154:

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

What's wrong with this? Why is it giving me that error?

1
  • $this does not exist in static functions. They only exist in class context, there is no object instance
    – knittl
    Commented May 1, 2013 at 19:03

3 Answers 3

7

Static methods do not belong to the instance of an object, $this relates to the instance...

In this instance I don't think you need anything other than to simply return the result of the hash (candidate for a lambda expression maybe?)

public static function generateCode($salt)
{
    return substr(hash('sha512', $salt), 0, 15);
}
2
  • 1
    @user2326532 sure, why not? Commented May 1, 2013 at 19:07
  • @user2326532 The access level of a method is separate from whether or not it is class or instance level.
    – Orbling
    Commented May 1, 2013 at 19:26
4

A static function means it is 'bound' to the class, not each instance (object). Call it like this:

  ClassName::generateCode($email);

Also, you cannot use object members in static functions. Make your $generate member also static, and refer to it as:

  ClassName::$generate 
5
  • It is in the same class, therefore I called it self::, I've read that you've to use self:: if its in the same class, However, It did not fix the error. Commented May 1, 2013 at 19:03
  • That's when the member is static, not the method. Commented May 1, 2013 at 19:04
  • 1
    You can use self:: or static:: when accessing internal class (static) methods, that is correct.
    – Orbling
    Commented May 1, 2013 at 19:07
  • @Orbling yes, but you cannot use self:: or static:: on non-static members. Commented May 1, 2013 at 19:08
  • @BartFriederichs: Aye, only static methods and properties. It's helpful to think of those two as the class level versions of $this.
    – Orbling
    Commented May 1, 2013 at 19:24
0

Inside your function you should use self instead of $this because the function is declared static.

Declare your member $generate as static, else it would not work.

Not the answer you're looking for? Browse other questions tagged or ask your own question.