2012-11-14 17:15


I'm have a DatabaseObject Class that has select, insert, update and delete methods defined. The purpose of the class is to represent a subset of rows in my MySQL database as a PHP object. The constructor calls MySQL's SELECT command and the destructor calls the DELETE command (unless I ask it not to).

Here is my DatabaseObject class:

class DatabaseObject {  
    protected $table;
    protected $index_field;

    private $data;

    function __construct($id) {
        //MySQL SELECT and assign resource to data

    function __destruct() {
        //MySQL UPDATE

    public function insert($data) {
        global $db;     //Database Class for using MySQL

        $fields = array();
        $values = array();

        foreach ($data as $field => $value) {
            $fields[] = "`".$field."`";
            $values[] = "'".$db->escape($value)."'";

        $sql = "INSERT INTO ".$this->table." (".join(', ', $fields).") VALUES (".join(', ', $values).")";
        if($db->query($sql)) {
            return $db->insertID();
        } else {
            return false;

    //More methods; update(), delete(), select()

I extend the DatabaseObject class when I want to access a specific table. For example, my User class is for my user table. Here it is:

class User extends Object {
    public static $anonymous_data = array('user_id' => 0, 'user_level' => ANONYMOUS, 'username' => 'Anonymous');

    function __construct($user_id = NULL) {
        global $db;
        $this->db = $db;

        $this->table = USER_TABLE;
        $this->index_field = 'user_id';


    function __destruct() {

    //Other user methods; login(), logout() etc.

Now, I would like to be able to call the insert method from the user class without having already instantiated the User class. I'm pretty sure, I have to make it static to do so. How do I make the insert method static, but still allow it to use the table which was defined in the extension class?

In other words, I want to be able to do this:

User::insert($data);        //INSERT into user table
AnotherClass::insert($data);    //INSERT into another table

...without instantiating either class.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doumi1311 doumi1311 9年前
    class Foo {
        public static $anonymous_data = array();
        public static function aStaticMethod() {
            self::$anonymous_data = array(key, value);
            foreach (self::$anonymous_data as $key => $value) {
                 echo "$key => $value";
    $classname = 'Foo';
    $classname::aStaticMethod(); // As of PHP 5.3.0

    For a static method. However be aware static variables CAN NOT be accessed this way. Read more about this example and the static key word here:

    Updated: Using self instead of $this-> example.

    点赞 评论 复制链接分享