在這一節中,我們將殺害二鳥一石。不僅我們將學習如何將面向對象的PHP和MySQL ,但是我們將學習如何組對象。在這種情況下,你將建立一個一流的UsersGroup其中將包含一系列的用戶對象。每個用戶對象將建立連續使用從MySQL查詢。要嘗試這個實際例子,您首先需要建立一個用戶表在MySQL數據庫。我使用的是MySQL數據庫命名為' kirupa_oop ` 。使用下面的查詢創建表並插入樣本數據。
/* Create Users table */
CREATE TABLE `users` (
`user_id` INT NOT NULL AUTO_INCREMENT,
`user_name` TEXT NOT NULL,
PRIMARY KEY (`user_id`)
);
/* Insert sample data into Users table */
INSERT INTO `users`
( `user_id`, `user_name` )
VALUES
( '', 'kirupa' ),
( '', 'bwh2' );
這非常簡單的表格只是有兩個欄目: ` user_id '和'用戶名' 。您不妨添加自己的名稱,此表為香料的事情了。
如所承諾的那樣,我們將創造一個UsersGroup類。該工作組將包含一系列的用戶對象,其中每一項創建使用數據從我們的MySQL的表。我所有的表格上的數據庫名為` kirupa_oop ` 。如果您的數據庫沒有名為' kirupa_oop ' ,您必須更改數據庫名稱中的設置階級所示。這裡是我們的UsersGroup階級的行動:
$group = new UsersGroup;
/* loop through our group, echo user names */
foreach( $group->getUsers() as $user ) {
echo $user->getName().'<br />';
}
/* User class, same as before */
class User {
private $name;
function __construct( $attribs ) {
$this->name = $attribs['name'];
}
/* name methods */
function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}
}
/* Contains a group of User objects */
class UsersGroup {
private $name; // name of group
private $group = array();// group of User objects
function __construct() {
/* Connect to DB using Settings */
$link = mysql_connect(
Settings::$DATABASE['host'],
Settings::$DATABASE['username'],
Settings::$DATABASE['password']
);
mysql_select_db ( Settings::$DATABASE['database'], $link );
/* Get table names from Settings class */
$tbl_users = Settings::$TABLES['tbl_users'];
/* Query */
$sql = "SELECTuser_id AS ID,
user_name AS name
FROM $tbl_users";
$result = mysql_query( $sql ) or die(mysql_error());
/* Adds user to group with each row of data */
while( $row = mysql_fetch_array($result) ) {
$this->addUser( $row );
}
}
/*
Add a user to Group
Does simple check to see if we pass an array (like $attribs)
or if we pass an object (like a User object)
*/
function addUser( $user ) {
if( is_object( $user ) ) {
array_push( $this->group, $user );
}
if( is_array( $user ) ) {
$noob = new User( $user );
array_push( $this->group, $noob );
}
return;
}
/* Returns the group (which is an array) */
function getUsers() {
return $this->group;
}
}
/* Holds our site settings */
class Settings {
static $DATABASE = array(
// change these as needed 'database' => 'kirupa