Frage

I get the following error when using the following class in my code:

Using $this when not in object context protected function

Here is my code:

<?php
class Sign {
    private $db;
    private $errors = array();
    private $passed = true;

    public function __construct() {
        $this->db = DB::instance();
    }

    public static function sign($alias, $password) {
        if(!self::exists($alias)) {
            self::signup($alias, $password);
        } else {
            self::signin($alias, $password);
        }
    }

    protected function exists($alias) {
        $stm = $this->db->prepare('SELECT * FROM users WHERE alias = ?');

        if($stm->execute(array($alias))) {
            return true;
        }

        return false;
    }

    protected function signup($alias, $password) {
        $salt = Hash::salt(32);

        $stm = $this->db->prepare('INSERT INTO users(alias, balance, password, salt, created_at)
                                   VALUES (:alias, :balance, :password, :salt, :created_at)');
        $stm->execute(array(
            ':alias'        => $alias,
            ':balance'      => 0,
            ':password'     => Hash::make($password, $salt),
            ':salt'         => $salt,
            ':created_at'   => date('Y-m-d H:i:s')
        ));
    }

    public function errors() {
        return $this->errors;
    }

    public function passed() {
        return $this->passed;
    }
}

Why am I getting this error? Line 20 is inside of protected function exists() where I use $this->db->prepare()

What would cause this to be happening? I tried changing some of the public, protected, etc. to no avail. I had them as private and protected still gives this error.

War es hilfreich?

Lösung

You can't mix and match static and instance like this. Your real problem comes in how you're calling exists:

public static function sign($alias, $password) {
    if(!self::exists($alias)) {
        self::signup($alias, $password);
    } else {
        self::signin($alias, $password);
    }
}

Unless you really need a static method here, you should probably create an object and call sign() as an instance method of that object.

You could also use sign() as a factory, but as in any programming, there are several ways to $cat->skin().

public static function sign($alias, $password) {
    $retVal = new Sign();
    if(!$retVal->exists($alias)) {
        $retVal->signup($alias, $password);
    } else {
        $retVal->signin($alias, $password);
    }
    return $retVal;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top