Following are some of the key points described later in this article:
As a beginner, I have come across this common thing that PHP developers tend to write one or more functions in the PHP files/scripts. As a matter of fact, I have also come across several projects (profitable ones) which were written with a few PHP files, very large ones, having all the code put in them in form of multiple functions. When learning PHP, it is OK to do in this way. However, for web apps to go to production, this may not be the recommended way. Following are some of the disadvantages of writing PHP scripts with just the functions in it:
To take care of some of the above issues, one should learn writing PHP using object-oriented manner, e.g., writing code in form of one or more classes. Writing PHP code using classes helps one should segregate similar looking functions in a class (Single Responsibility Principle) and use the class elsewhere in the code (different PHP scripts). As a matter of fact, one could easily follow SOLID principle with PHP and make the code well-structured. Doing this way does propagate high maintainability (high testability, high cohesiveness, high reusability etc) and makes code readable and understandable.
Following are some of the key aspects of a PHP class:
That is it!
Following is the code example of a PHP class, User. Pay attention to some of the following:
class User {
private $name;
private $age;
function __construct( $name, $age ) {
$this->name = $name;
$this->age = $age;
}
function getName() {
return $this->name;
}
function isAdult() {
return $this->age >= 18?"an Adult":"Not an Adult";
}
}
Save the file as User.php. Don’t forget to put the above code within <?php and ?>
Finally, its time to use the PHP class. If you are working with a sample project, go to index.php. Assuming that User.php is saved in same folder as index.php, following is how the code would look like. Pay attention to some of the following:
<?php
require "User.php";
$h = new User( "Calvin", 15 );
echo "Hello, " . $h->getName(). "! You are ". $h->isAdult();
?>
<br/>
<?php
$h = new User( "Chris", 39 );
echo "Hello, " . $h->getName(). "! You are ". $h->isAdult();
?>
When working on a machine learning project, one of the key challenges faced by data…
Last updated: 1st May, 2024 The bias-variance trade-off is a fundamental concept in machine learning…
Last updated: 1st May, 2024 As a data scientist, understanding the nuances of various cost…
Last updated: 1st May, 2024 In this post, you will learn the concepts related to…
Last updated: 26th April, 2024 In this blog post, we will discuss the logistic regression…
Last updated: 22nd April, 2024 As data scientists, we navigate a sea of metrics to…
View Comments
http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/