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 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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@user2326532 sure, why not?
@user2326532 The access level of a method is separate from whether or not it is class or instance level.
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 Comments

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.
That's when the member is static, not the method.
You can use self:: or static:: when accessing internal class (static) methods, that is correct.
@Orbling yes, but you cannot use self:: or static:: on non-static members.
@BartFriederichs: Aye, only static methods and properties. It's helpful to think of those two as the class level versions of $this.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.