未捕获错误:不在对象上下文中时使用$ this

时间:2018-05-10 19:29:15

标签: php

我知道这个问题已被问了一千次,但我仍然不明白为什么这不起作用,

我正在尝试创建三个类,第一个是连接

<?php

namespace Core;

/**
 * 
 */
class connect
{
        private const DB_NAME = "vp_test";
        private const DB_USER = "root";
        private const DB_PASSWORD = "";
        private const DB_HOST = "localhost";

    function __construct()
    {

        $con= mysqli_connect(self::DB_HOST, self::DB_USER, self::DB_PASSWORD,self::DB_NAME);

        if (!$con){

             die("connection error: ". mysql_connect_error());
        }

    }
}
  

第二类是模型类

<?php

namespace Core;

require "autoload.php";

use Core\Connect;
/**
 * 
 */
class Model
{
    private $con;
    public $table;

    function __construct()
    {
        $this->con = new Connect;
        $this->table;

    }

    public function all(){

        $sql = "SELECT * FROM {$this->table}";

        return self::execute($sql);

    }

    public function query($select, $where = false){

        if($where){

            $sql = "SELECT {$select} FROM {$this->table} {$where}";

        }
        else{

            $sql = "SELECT {$select} FROM {$this->table}";
        }

        return self::execute($sql);

    }

    // fetch a single record
    public function find($id){

        $find =self::query("*", "WHERE id = {$id}");

        return $find;
    }

    private function execute($sql){

        $query = mysqli_query($this->con, $sql);

        $row = mysqli_fetch_assoc($query);

        return $row;
    }
}
  

第三个是扩展模型类

的用户类
<?php

namespace App;

require "./Core/autoload.php";

use Core\Model;

/**
 * 
 */

class User extends Model
{
    private $con;
    private $model;

    function __construct()
    {
        $this->model = new Model;
        $this->model->table = "users";


    }

    public static function getUsers(){


        $users = self::all();

        return $users;


    }

    public static function getOneLevel($level){

        $level = self::query("*", "WHERE level = {$level}");
        return $level; 
    }

    public static function getLevel($id){

        $level = self::query("level", "WHERE id= {$id}");

    }

    public static function getParent($id){
        $child = self::find($id);
        $id = self::query("id", "WHERE username = {$child["sponsor_username"]}");

        $parent = self::find($id);

    }

    public static function getChildren($id){

        $parent = self::find($id);

        $child = self::query("*", "WHERE sponsor_username ={$parent["username"]} ");
    }


}

我希望用户类实例化模型类然后传递表名,但它不断给出错误,如上所述,我已经大量编辑了上一个类,我仍然没有问题是什么,我知道这只能在对象上下文中使用,这就是我在用户类的构造函数中实例化模型的原因。 任务https://github.com/Thirdwrist/database-task

的链接

0 个答案:

没有答案