Tutorial How to Create a Basic PHP Class

Ghost

Active Coder
Moderator
Apr 19, 2019
324
149
43
In this tutorial you will learn how to create a simple PHP class.
Classes are used for many reasons, including but not limited to the following:
  • Re-usability through the core system
  • Organization
  • Easier to manage long-term due to data (ex: user profile info) going through a defined class / set of functions... instead of "spaghetti code" appearing all over the system
  • Easy to code, even easier to use
If you have not yet learned how to create a PHP function, check out my tutorial How to Create a Function in PHP. You will need to know a bit about functions before you can move on to classes.

Creating a Class
PHP:
<?php
class Person{
   
}  
       
?>
That simple code will let you define a class in PHP. You can then require/include this class file in other files to use the class.
You should create a new file for your class. Let's name ours Person.php in our /classes/ folder

Person.php
PHP:
<?php
class Person{

  public function __construct(){
   
  }

} // end of Class
?>
We start off with the public construct. This lets us do things with our class as soon as we use it in our script.
The public construct is declared with:
public function
followed by __construct()
That's two underscores _ _ c o n s t r u c t ( )

Let's look at an example of "doing something" in our public construct for our Person class.
Person.php
PHP:
<?php
class Person{

  public function __construct(){
    echo "I am a person";
  }

} // end of Class
?>
So right now, if we used our Person class, we would see "I am a person" echo'd out on to the page.
Let's take a look at how to use our class before we continue.

PHP:
<?php
class Person{

  public function __construct(){
    echo "I am a person";
  }

} // end of Class

$Joe = new Person();
?>
If you open this file up in a PHP-ready system, you will see the output.
This code here is saying that we want the variable $Joe to be a new instance of the Person class.
When we do this, the public construct is triggered immediately, and "I am a person" echos out on to the page!

However, we would not use a class in this fashion. It's much better to use functions to handle events or logic for our class. Additionally, it's better to have your class return information and messages instead of handling things like an echo. We'll look at an example of this below...

PHP:
<?php
class Person{

  public function __construct(){
    $this->error = false;
  }

  public function setName($name){
    $this->name = $name;
  }

} // end of Class

$Joe = new Person();
$Joe->setName("Joe");
echo "Their name is: $Joe->name";
?>
If we open this file up, we only see "Their name is: Joe". As you can see, we were able to set the name & use it afterwards quite easily.
Let's look at a more practical example. It's also worth noting that you do not even need to set all class variables up inside the class. You can also do this...

PHP:
<?php
class Person{

  public function __construct(){
    $this->error = false;
  }

  public function setName($name){
    $this->name = $name;
  }


} // end of Class

$Joe = new Person();
$Joe->setName("Joe");
echo "Their name is: $Joe->name <br />";

$Joe->age = 26; // no function required

$Person2 = new Person(); // create a new person
$Person2->name = "Chris"; // set their name without a function
$Person2->age = 30; // set their age without a function

echo "$Person2->name is $Person2->age years old."; // use our class info in a sentence.
echo "$Joe->name is $Joe->age years old.";
?>
As you can see, we didn't use the name function or an age function. We were still able to set the variables & then use them later on in a sentence.
However, you might be struggling to see how this is useful. Well, we can take all of this a step further by comparing some of the info between our two instances of the Person class. We have Chris and Joe, but the same class code is handling both of our people.

PHP:
<?php
class Person{

  public function __construct(){
    $this->error = false;
    $this->age = false;
    $this->name = false;
  }

  public function setName($name){
    $this->name = $name;
  }

  public function setAge($age){
    if(is_int($age)){ // age is a valid number:
      $this->age = $age;
      return true;
    } else { // age is not a valid number:
      $this->error = "You must supply a valid integer for the age.";
      return false;
    }
  }


} // end of Class

$Person1 = new Person();
$Person1->setName("Joe");
$Person1->setAge(26);

$Person2 = new Person();
$Person2->setName("Chris");
$Person2->setAge(30);

if($Person1->age == false || $Person2->age == false){ // if an error was found in our class
  echo "You must set the ages of both people.";
} else if($Person1->age > $Person2->age){
  echo "$Person1->name ($Person1->age Yrs) is older than $Person2->name ($Person2->age Yrs)";
} else if($Person2->age > $Person1->age){
  echo "$Person2->name ($Person2->age Yrs) is older than $Person1->name ($Person1->age Yrs)";
} else { // same age:
echo "$Person1->name and $Person2->name are the same age ($Person1->age Yrs).";
}
?>

In this latest block of code, we give the FALSE value for our intiial name & age values. We do this in the public construct. That way we can detect if the age/name was not set for some reason later on. You will also notice that I altered the class variable in use from $Joe to $Person1. I also use the functions for setAge so that we can properly analyze the given age. We make sure it is a valid integer for their age so that there are no problems later on with our number comparisons.

Then we actually go and look to see if the age is false for either of them. If an age is false, a non-integer was used in setAge(#) OR the programmer forgot to use setAge(). It's also a failsafe measure for user supplied data or information coming from another source. Occasionally data can become corrupted or formatted incorrectly, so having small checks like is_int() can go a long way.

Once we know both ages are set, we compare them to see who is older.
Because Chris is 30 and Joe is 26, our sentence reads:
Crhis (30 Yrs) is older than Joe (26 Yrs)

So, hopefully you can see how classes are useful. Remember, the class file can significantly improve code by forcing all coded pages to use the "Person" or "Account" class file to create, edit, or delete information for a profile. Without defined functions or classes, programmers are forced to manage countless & unnecessary files that are all pretty much doing the same thing. It is much better to only have to manage the HTML views, sets of controllers (to accept data from unique forms & pages), and then use classes to manage the actual core logic, integration with the database, or anything that needs to remain consistent across the entire site.

Imagine the following...
In a few weeks from now, I want to modify the Person class. Well, I could alter it so that $Person1->age is actually taken from data saved in a file, or in a database. If setAge() is used, I can alter the class to actually change the database value for that person/user's age. With a class, I just alter the class file & it will work for the rest of the system.

That's easy, but imagine the flip side... without using a class...
Your website has 15 different pages that pull the user's name & age. Suddenly, you have to change the protocol for how you save / where you save that data. Instead of altering 1 class file that handles all of it, you now need to edit all 15 of those pages to make the change.

Those two scenarios should hopefully help you understand why class files save us time :)
Our class files at Wubur, our web development company, can be huge and they are much more complicated than the examples in this tutorial. However, the principles of a class can be learned in this article, so hopefully it helps you on your journey in PHP. Let me know if you need any help!
 
Last edited:

Shole

New Coder
Apr 19, 2019
10
1
1
Nice one, I will try it out as soon as I get home to recreate it and play with this. Thanks a bunch for this!
 

Brad

New Coder
May 9, 2019
14
2
3
You're converting the variables from boolean to an int or a string why? Set them to 0 or null by default, you can do the error checking solely with the $error variable you've created.

PHP:
<?php
class Person
{
    // Should declare the variables here...
  public $error = null;
  public $age = 0;
  public $name = null;
    
  public function __construct()
  {
    // No Longer needed, unless you want to make creating the Person quicker
    // then allow them to provide name and age here and return $this
    /**
     * $this->name = $name;
     * $this->age = $age;
     * return $this;
     */
  }

  public function setName($name)
  {
    $this->name = $name;
  }

  public function setAge($age)
  {
    if(is_int($age))
    {
      $this->age = $age;
      return true;
    }
    else
    {
      $this->error = "You must supply a valid integer for the age.";
      return false;
    }
  }


} // end of Class

$Person1 = new Person();
$Person1->setName("Joe");
$Person1->setAge(26);

$Person2 = new Person();
$Person2->setName("Chris");
$Person2->setAge(30);

// Also note that you where not using the $person->error anywhere before.

if(!is_null($Person1->error) || !is_null($Person2->age))
{
  echo "You must set the ages of both people.";
}
else if($Person1->age > $Person2->age)
{
  echo "$Person1->name ($Person1->age Yrs) is older than $Person2->name ($Person2->age Yrs)";
}
else if($Person2->age > $Person1->age)
{
  echo "$Person2->name ($Person2->age Yrs) is older than $Person1->name ($Person1->age Yrs)";
}
else
{
  echo "$Person1->name and $Person2->name are the same age ($Person1->age Yrs).";
}
 

Ghost

Active Coder
Moderator
Apr 19, 2019
324
149
43
You're converting the variables from boolean to an int or a string why? Set them to 0 or null by default, you can do the error checking solely with the $error variable you've created.

PHP:
<?php
class Person
{
    // Should declare the variables here...
  public $error = null;
  public $age = 0;
  public $name = null;
   
  public function __construct()
  {
    // No Longer needed, unless you want to make creating the Person quicker
    // then allow them to provide name and age here and return $this
    /**
     * $this->name = $name;
     * $this->age = $age;
     * return $this;
     */
  }

  public function setName($name)
  {
    $this->name = $name;
  }

  public function setAge($age)
  {
    if(is_int($age))
    {
      $this->age = $age;
      return true;
    }
    else
    {
      $this->error = "You must supply a valid integer for the age.";
      return false;
    }
  }


} // end of Class

$Person1 = new Person();
$Person1->setName("Joe");
$Person1->setAge(26);

$Person2 = new Person();
$Person2->setName("Chris");
$Person2->setAge(30);

// Also note that you where not using the $person->error anywhere before.

if(!is_null($Person1->error) || !is_null($Person2->age))
{
  echo "You must set the ages of both people.";
}
else if($Person1->age > $Person2->age)
{
  echo "$Person1->name ($Person1->age Yrs) is older than $Person2->name ($Person2->age Yrs)";
}
else if($Person2->age > $Person1->age)
{
  echo "$Person2->name ($Person2->age Yrs) is older than $Person1->name ($Person1->age Yrs)";
}
else
{
  echo "$Person1->name and $Person2->name are the same age ($Person1->age Yrs).";
}
You're right, but this was just intended to show classes working. the actual content of the data is supposed to be somewhat irrelevant to the tutorial, it just shows how the functions operate.
 

Brad

New Coder
May 9, 2019
14
2
3
You're right, but this was just intended to show classes working. the actual content of the data is supposed to be somewhat irrelevant to the tutorial, it just shows how the functions operate.
I understand but if it's a tutorial for new developers, it's probably best to teach them the best and latest practices.