📖 PHP Classes and Objects
One of the central tenets of Object Oriented Programming (OOP) is the use of classes and objects as organizational structures. These components of a OOP project are used to compartmentalize and organize the code. When we need a component in a project, it is often used repeatedly. Sometimes the component will take on variations from a base model. In these instances, it is beneficial to create a 'template' of the component definition and store it in a class. The class in this case becomes the container for the template definition that includes the component's properties (attributes) and methods (functions). We use the class template to create instances of objects for use in the project. The object becomes the working instance of the class definition.
You may have heard a description of classes and objects as something like using a blueprint as a plan for a house and the house as the instance of the plan. This metaphor is effective in describing the basic function of the OOP classes and objects. You can have a blueprint of a house but you cannot live in a blueprint. You use the blueprint (class) to create the house (object). Like blueprints, classes are used as a plan but can be modified during construction.
Think of classes as plans and objects as things built from those plans. We don't use plans to run our programs, we use objects created from the plans to run our programs. This allows us to create any number of instances of objects based on a plan and to modify the plans for specific purposes.
<?php
// create a class named User
class User
{
// create a couple of properties
public $name = "Stephen";
// create a method named greeting
public function userGreeting()
{
return "Greetings " . $this->name;
}
}
// create a new (object) instance of the User class
$greeting = new User;
// call the greeting() method of the new $greeting1 object
echo $greeting->userGreeting();
Visibility
Classes can include visibility modifiers for properties (variables), methods (functions) and constants. This is a property of the class that tells the program to whom the class can be accessed. Review the PHP docs for more information on visibility modifiers.
There are 3 class visibility modifiers.
- public: this is a common setting that allows the element to be accessed from anywhere in the program.
- private: this is a setting that limits the access to only the parent class.
- protected: this setting allows the element to be accessed from the parent class and any class that extends the parent class.
To review, classes are the plan for the building of objects. They contain properties (variables) and methods (functions). Classes can extend other classes and objects can be created based on the class definition (content) each time inheriting the properties and methods of the parent class.
PHP Coding Standards
PHP has its own ecosystem with developers from around the world. It has evolved from the 'Personal Home Page Tools' of Rasmus Lerdorf in 1994 to a widely used full function programming language of today powering millions of websites. A benefit of this much use and attention is the refined nature of a mature coding language. PHP has many communities using and supporting the language, but one very important group is the PHP Framework Interop Group. This group provides collaboration and development of the PHP language and documents the PHP Proposed Standards Recommendations for adoption into the framework.
One of the first things you should know is that there are specific guidelines for writing PHP OOP applications that should be adhered for compatibility. If you are writing your own application completely, you might be able to diverge from these recommendations, however, your app may not work with other apps used as dependencies. You won't be able to integrate third party tools.
You should review and become familiar with the recommendations of the PHP-FIG starting with the PSR-1: Basic Coding Standard. This document describes the best practices for using PHP tags, organizing your code and naming conventions for the different elements of your code. Pay particular attention to the naming convention for classes, constants and methods. Notice the code above uses StudlyCaps
for the class name User and camelCase
for the method name userGreeting.
-
Class names MUST be declared in
StudlyCaps
akaPascalCase
. -
Method names MUST be declared in
camelCase
. -
Class constants MUST be declared in all upper case with underscore separators
SCREAMING_SNAKE_CASE
. The underscores are known as snake case and the uppercase letters represent the screaminng. So, basicsnake_case
would be in lowercase. In either case, avoid using leading underscores as they are generally associated with built-in (reserved) language elements. -
URL slugs are often written in
kabab-case
to create more human-readable consistent text.
Database Connection Script Example
To see this in context, consider the following database connection script using PHP built-in PDO object. PDO stands for PHP Data Object and is used for connecting to a variety of databases using PHP. There are also many vendor-specific connection scripts that are available in the PHP library. You can reference the PHP docs for more information on the PDO library.
<?php
// setup connection details
$dsn = "mysql:
host=localhost;
dbname=adv_php;
charset=utf8;
port=3306";
// create new PDO connection object with error messaging turned on
$pdo = new PDO($dsn, "adv_php_user", "secret", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
// create the db query in the PDO and assign it to a variable
$stmt = $pdo->query("SELECT * FROM `products`");
// run the query using the PDO connection and return the result to a variable
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
// output the results
print_r($products);
In reviewing the above script, you should notice there are some details that must be in place for the script to return the requested data. First, the database must be set up to match the calling script. Notice the host and dbname are provided to the $dns (Data Source Name) variable to define the location and name of the database. Also, notice in creating the new PDO the username and password are passed to the connection script.
The database must be created and configured to meet the specifications shown in the script.
- host: localhost (most common connection host used when the db is on the same server as the calling script)
- dbname: the name of the database
- username: "adv_php_user" must be created and assigned db permissions
- password: "secret" represents a secret password (this is not a secure password)
Creating the Database
Below is a script used to create a database that would meet the connection requirements of the script above.
-- create a new database named adv_php
CREATE DATABASE adv_php;
-- select the new db
USE adv_php;
-- create a new table named products
CREATE TABLE products (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(128) NOT NULL,
description TEXT NULL DEFAULT NULL,
PRIMARY KEY (id)
);
-- assign user usage privileges
CREATE USER 'adv_php_user'@'localhost' IDENTIFIED BY 'secret';
-- assign database privileges to user
GRANT ALL PRIVILEGES ON adv_php.* TO 'adv_php_user'@'localhost';
-- insert new records into the products table
INSERT INTO products (name, description)
VALUES ('First Product', 'This is the first product'),
('Second Product', 'A second product goes here'),
('Product Number 3', ''),
('Last of the Original Products', 'A description with <strong>HTML</strong>.');
If you want to test these scripts, first open phpMyAdmin and run the SQL script above. Then create a new file with the PHP script above. Run the PHP script from a web server to see the results. You should see a list of products that match the details found in the new products table.
Viewing the Database Result Set
The result of the above database and connection script will be a multidimensional array consisting of the data records from the products table. Using the print_r()
function, the result set will look something like this in your browser.
Array ( [0] => Array ( [id] => 1 [name] => First Product [description] => This is the first product ) [1] => Array ( [id] => 2 [name] => Second Product [description] => A second product goes here ) [2] => Array ( [id] => 3 [name] => Product Number 3 [description] => ) [3] => Array ( [id] => 4 [name] => Last of the Original Products [description] => A description with HTML. ) )
If you right-click the page and select View [Page] Source in your browser, you should see a more readable format of the output result set array.
Array ( [0] => Array ( [id] => 1 [name] => First Product [description] => This is the first product ) [1] => Array ( [id] => 2 [name] => Second Product [description] => A second product goes here ) [2] => Array ( [id] => 3 [name] => Product Number 3 [description] => ) [3] => Array ( [id] => 4 [name] => Last of the Original Products [description] => A description with HTML. ) )
Formatting the Output into HTML
Now that we have the result set from the db in an associative array, it is fairly straight forward to format the data in an HTML page. Simply remove the previous print_r()
function and close the PHP tag ?>. Then, below the PHP database script, add the HTML with an embedded foreach
loop to display the contents of the db table in a formatted HTML page.
<?php
$dsn = "mysql:
host=localhost;
dbname=adv_php;
charset=utf8;
port=3306";
$pdo = new PDO($dsn, "adv_php_user", "secret", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$stmt = $pdo->query("SELECT * FROM `products`");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Products</title>
</head>
<body>
<h1>Products</h1>
<?php foreach ($products as $product) : ?>
<h2><?= htmlspecialchars($product["name"]) ?></h2>
<p><?= htmlspecialchars($product["description"]) ?></p>
<?php endforeach; ?>
</body>
</html>