PHP classes use instances of data classes tutorial

Source: Internet
Author: User

In this section, we will kill two birds a stone. Not only will we learn how to target object-oriented PHP and MySQL, but we will learn how to group objects. In this case, you will build a first-class usersgroup which will contain a series of user objects. Each user object will be established for continuous use from MySQL query. To try this practical example, you first need to build a user table in the MySQL database. I'm using the MySQL database named ' Kirupa_oop '. Use the following query to create a table and insert sample data.

/* 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 ');

This very simple form only has two columns: ' user_id ' and ' username '. You may wish to add your own name to this table for spice things up.

As promised, we will create a Usersgroup class. The workgroup will contain a series of user objects, each of which creates a table using data from our MySQL. The database on all my forms is named ' Kirupa_oop '. If your database does not have a name of ' Kirupa_oop ', you must change the setting class in the database name as shown. Here is the action of our Usersgroup class:

$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 = "Select user_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 the if we pass a array (like $attribs)
Or if we pass is 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 a array) * *
function Getusers () {
return $this->group;
}
}

* * Holds our Site Settings */
Class Settings {
Static $DATABASE = Array (
Change these as needed ' database ' => ' Kirupa

The first thing to show is that we hold our database connection and table name set in our country class, in static variables. If we need to change our database name, table name, database username, etc., we will only be able to do that we set the class (which is best in a separate, including file). Our user level is nothing new-it not only owns the name of the property, still gets a series of data via _ _construct.

Let's take a look at the code Usersgroup class. If you have connected to the MySQL database with PHP before, the connection should be something new. The only difference is that we use static variables for our connection settings. We do this on our name, because the double quotes inside the table, our set class static variable cannot be parsed. That is, only the use of settings:: $ table [' tbl_users '] directly in our double quotes SQL query will result in an error.

Our SQL query produces a series of rows that we specify as the result. Using the while loop, we pass our $ result array. The result of each element dollar is a series of values (such as number and name). Again, this should look familiar to people who use PHP to access the MySQL database. Now the object-oriented part: We then query our AddUser method from our MySQL through each row (column). First, the AddUser method checks if it is passed through a series of data (such as $ rows) or an entire user object. In this case, we are going through a series of data. Using this array of data, AddUser creates a user object ($ noob), and then adds the user object's group array ($ group).

Note to the column name: When our user goal is to build a series of data, the construct is to find the name of the so-called array element. To meet this requirement, we use the SQL alias to see the dollar database. If we do not have an alias username name in dollars the contiguous variable will not hold the name of the so-called array element, but the username. Therefore, it does not correctly fill in the name of the variable in our user object. I would rather let me customize the SQL instead of my PHP class method because I am more likely to reuse PHP class methods than SQL queries. For example, if I create a dog class, I would also like to getname methods and constructs. Instead of modifying several PHP methods to support the user rather than the dog, I would rather modify an SQL query. Alternatively, you can rename your user name bar, just the name. This will maximize reuse, but may hurt your ability to understand more complex SQL queries and database designs.

You may consider this category to be too complex. After all, you probably code all of this in 15 lines of regular PHP pages. So, where's the advantage? Well, let's see how we use our objects:

/* Instantiate Group * *
$group = new Usersgroup;

/* Loop through our group, echo user names * *
foreach ($group->getusers as $user) {
echo $user->getname (). ' <br/> ';
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.