dropbox1111 2017-04-24 09:52
浏览 61
已采纳

对PHP OOP范围感到困惑

I'm trying to re-write my PDO MySQL class, it's using a form of dependency injection.

Here's how it connects:

public function __construct($dsn, $username, $password)
{
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_STATEMENT_CLASS => array("EPDOStatement\EPDOStatement", array($this)),
        PDO::ATTR_EMULATE_PREPARES   => false, // allows LIMIT placeholders
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
    ];
    parent::__construct($dsn, $username, $password, $options);
}

Then it's called like this:

$dbl = new db_mysql("mysql:host=".$db_conf['host'].";dbname=".$db_conf['database'],$db_conf['username'],$db_conf['password']);

Now, inside another class named "core" it has this in the __construct:

class core
{
    public $database;
    function __construct($database)
    {   
        $this->database = $database;
    }

public static function config($key)
{
    if (empty(self::$config))
    {
        // get config
        $get_config = $this->database->select("config", '`data_key`, `data_value`');
        $fetch_config = $get_config->fetch_all();

        foreach ($fetch_config as $config_set)
        {
            self::$config[$config_set['data_key']] = $config_set['data_value'];
        }
    }

    // return the requested key with the value in place
    return self::$config[$key];
}
}

That's called like so:

$core = new core($dbl);

So it's taking the database connection, and assigning it to $database which is set to "public" inside the core class. The problem is when I call the config function, I get this error:

PHP Fatal error:  Uncaught Error: Using $this when not in object context

It mentions the error comes from the line

"$this->database->select" inside the "config"

function.

  • 写回答

2条回答 默认 最新

  • doutandusegang2961 2017-04-24 09:56
    关注

    Your config method is static.

    Static Methods can be accessed without an object being instantiated and so $this isn't an available handle to the current object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?