在这一节中,我们将杀害二鸟一石。不仅我们将学习如何将面向对象的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