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';
parent::__construct($user_id);
}
function __destruct() {
parent::__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.
<?php
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";
}
}
}
Foo::aStaticMethod();
$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: PHP.net
Updated: Using self
instead of $this->
example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.