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 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型