1

我在扩展类时遇到问题。

这就是我想要做的:

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 ..." );
    }
}

所以,这就是结构,但我的问题是我收到以下错误:

致命错误:在第 10 行的 /Applications/XAMPP/xamppfiles/htdocs/own/newsite/classes/class.Functions.php 的对象上下文中使用 $this

我能做些什么来解决这个问题?

4

1 回答 1

3

声明create_user为非静态并从实例中调用它,否则(如错误消息所述)您无法访问 $this,因为 $this 始终是对当前实例的引用。在静态上下文中,没有一个。

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

代替

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.

于 2012-06-02T23:20:51.030 回答