views:

150

answers:

2

why I can't do like this?

<?php 
class core {
    public static $db;


    function __construct() {
        $this->db = new mysql('host', 'user', 'pw', 'db');
    }
}

class stat extends core {
    public static function log() {
        core::$db->query("insert into mytable values(now())");
    }
}

// do something
stat::log(); 
?>
A: 

By the looks of your code, because you don't assign anything into $db. The constructor is only called when you create an instance of the class, not with statics.

Also, why is your code even extending core? You don't need to extend it to use static methods/variables. Perhaps it would make more sense to actually make it an instance property, and use a new instance instead of static?

Jani Hartikainen
A: 

The core::__construct() method is only called when you call new core or new stat, invoking the creation of an object. You go straight to stat::log(), so core::$db has never been initialized.

Ewan Todd