简体   繁体   中英

Error when Extending a class

Im having problems extending a Class.

This is what I was trying to do:

class Core
{
    protected $db;

    public function __construct()
    {
            $this->set_db_class();
    }

    private function set_db_class ()
    {
        include_once ( './classes/Database.php' );
        $this->db   = new Database();
    }
}


class Functions extends Core
{
    public function __construct()
    {
                parent::__construct();
    }

    public static function create_user ()
    {
        $this->db->query ( "INSERT ..." );
    }
}

So, that's the estructure, but my problem is that I'm getting the following error:

Fatal error: Using $this when not in object context in /Applications/XAMPP/xamppfiles/htdocs/own/newsite/classes/class.Functions.php on line 10

What can I do to solve this?

Declare create_user as non-static and call it from an instance, otherwise (as the error message says) you cannot access $this, since $this is always a reference to the current instance. In a static context, there isn't one.

$functions = new Functions();
$functions->create_user();

instead of

Functions::create_user();

If you want to bundle functions that are not logically related to each other, use a namespace and not a class. You can go with an all-static class (every tiny property and method is static so that you don't need an instance at any time), but that's a horrible solution and not what classes should be used for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM