PHP process-oriented and object-oriented

Source: Internet
Author: User

PHP program writing is divided into process-oriented and object-oriented. There is no difference in the implementation of the function, but in code writing is very different, the process-oriented code is very messy, difficult to manage, and object-oriented to encapsulate common functions as a class, so the code is much clearer.

Here is a small example to illustrate:

PHP Connection Database:

Process-oriented: $conn = mysql_connect (' Server name ', ' Database login name ', ' password ') or Die (' connection unsuccessful! ');
mysql_select_db (' Library name ', $conn) or Die (' database does not exist! ‘);
$queryid = mysql_query ("Select * from sort");
while ($rs = Mysql_fetch_assoc ($queryid)) {
echo $rs [' name '], ' <br> ';

Object-oriented: 1. Build a php file called db.php, which encapsulates the above code into a class:

Class DB {
Private $conn; Property
Private $queryid; Property
constructor function
Public Function db ($host, $dbuser, $DBPASSWD, $dbname) {
$this->conn = mysql_connect ($host, $dbuser, $dbpasswd) or die (' Connection not successful! ');
mysql_select_db ($dbname, $this->conn) or Die (' database does not exist! ‘);
}
Query method
Public Function Query ($sql) {
$this->queryid = mysql_query ($sql, $this->conn);
}
Public Function Fetch_assoc () {
Return Mysql_fetch_assoc ($this->queryid);
}
}

2. Instantiation in the a.php file, code usage becomes simple and easy to understand, code reusability
Inclode (' db.php ');
$db = new db (' Server name ', ' Database login ', ' password ', ' library name ');
$db->query ("select * from sort");
while ($rs = $db->fetch_assoc ()) {
echo $rs [' name '], ' <br> ';
}

PHP process-oriented and object-oriented

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.