Classes and OOP (Part 1)

1.0 Introduction to Tutorial

This tutorial is made in assumption the user has basic working knowledge of PHP. If not, you might want to start learning here. (This is NOT part 2 of that tutorial).

This tutorial would (most likely) be broken down into bits since this topic is fairly huge and it's not possible to explain and go through everything adequately in one tutorial (unless the tutorial is extremely huge).

1.1 Introduction to Classes

Classes play a huge role in systems today and help create and maintain advanced programs/systems/apis.

A class is like a collection, or a library of functions and variables within the class that are aimed at performing one role (or aiding in one specific role). Each different role/category would have it's own class as needed, and all the members of the class (functions, variables) would perform their portion of the task (their chores) to arrive at a successful completion of the task (or it would display an error).

A class is made up of members such as functions and variables... or you could say the class is defined with the members in it.

Each function could be called on within and outside the class and the class variables could be used within and outside the class. Even though you could use the class members within and outside the class and they would perform the same, the way you call on them would change. You could pass, use and instantiate other class objects within a class to perform/aid to perform a required task.

There is no limit to how big your class could be and you don't have to use them all (though I don't see a purpose to have a function and not use it besides planned additional development).

1.2 Introduction to OOP

OOP stands for Object-Oriented Programming and is mainly a group of many (or a collection of) classes performing different roles to create a single system/program. An example of a system based on OOP would be phpBB (Though not the best example).

There are many different types of programming patterns out there (or lack thereof) and different accepted ways to practice OOP and I will try my best to provide you/teach you the most up-to-date best way to write in OOP. (If you notice something that is considered bad practice and/or have/know an improvement, please let me know that in the comments below).

Let me point out that you could have just a class and it not being considered as OOP, since OOP means that the entire system is oriented around objects.

An object is an initiated instance of a class and would be set to a variable. All of that class's members (such as functions and variables) would be accessed through that variable holding the instance of a class with an arrow (->).

For example:

// Initiating the class (making an object)
$object = new class();

// Accessing the class's function
$object->classFunction();

// Accessing the class's variable
$object->classVariable;

Don't worry what the code does, where the class is defined or anything at all... those lines of code we provided as an example of how you would call on objects. Everything would be later explained in more detailed, and after this tutorial you should be able to come back here and understand a bit more on what you're looking at here.

2.0 Lexical Structure

Just like the main language we are using (PHP) which has "grammar" telling the programmer how to write in that language, each different part of PHP and each feature made accessible in PHP has those rules.

Like starting a conversation with 'Hi' and ending it with 'Bye', we start a class with the word "class" and end it with a curly end bracket "}", but that is not all, right after the word "class" we would provide the name for that class and an open curly bracket "{".

For example:

class fruit
{

}

What that does is the entire lines 1 and 2 is how you would normally start defining a class and line 4 would be how you would end the definition for the class. Basically (or in other words) you would wrap the class's definition with that.

The reason why I said that is how you would normally start defining a class is because there are different types of classes that people use and they all behave a bit differently from each other. They are made to perform different types of tasks then the other types.

Mainly, what I'm talking about are abstract, interface, trait and final. Each has their own purpose and behave differently then the other. We would come back to these a bit later on in the tutorial.

2.1 Functions and Variables

It is time to start defining our class and adding some class members such as functions and variables to it. They too, have a certain lexical structure to them, which we have to follow in order to create the class definition. Let's see what it is.

class fruit
{

    function eat()
    {
        // Chew
    }

}

You would notice that the way you would start the definition of a function is very similar to how you would start and end a class. Right before the name of the function you have the word "function" (instead of "class", since it's a function) and it has those curly brackets "{ ... }" except there is one difference... the parenthesis in there right after the function name.

Where I put the comment (// Chew) you would have the code that performs that action.

Line 4 is how you would start to declare the function and line 7 is how you would end the definition of the function. All of the PHP code that would be run once the function would be initiated are in between the curly brackets "{ ... }".

Also, I want you to notice the way I have spaced and organized the code and where everything is located. You don't necessarily have to have it that way, instead of 2 lines to start classes and functions you could move the open curly brackets and have it be the last in 1 line (next example) and it would work the same way, but what I have found out (and what many others do) is that it is easier to read the code if they are spaced the way I have it in the previous example. It's also a better practice to do it this way, because not only is it easier to read the code, but it is also easier to maintain and edit the code for you, or any other programmer maintaining/editing code you wrote. I think this applies to every language, not just PHP. (Bad spaced and organized code is comparable to obfuscation).

class fruit {

    function eat() {
        // Chew
    }

}

So far, we have only added a function, now let's add a variable.

class fruit
{

    var $amount;

    function eat()
    {
        // Chew
    }

}

In this example we only define the variable $amount;, we don't have it set to any information yet. We could though, for instance we have a surplus of apples and we could eat 2 of them per sitting (or, by default, in other words).

class fruit
{

    var $amount = 2;

    function eat()
    {
        // Chew
    }

}

So far, we have stuck to the basic simple stuff of how to set-up a class.

2.2 Initiating and Using Classes

Now that we have defined a class and set a function and a variable there that we could use, we could now go ahead and initiate the class and start using it's function and variable. Below is a simple example of how we would start using the class we have written.

// Initiating the class (making an object)
$product = new fruit();

// Setting the amount of fruit
$product->amount = 1;

// Eating the fruit
$product->eat();

In that example, the second line is where we actually initiate the object and set it to a variable, so $product is now holding the class object and we would be accessing all of the class's functions and variables through this variable.

At line 5, we set the amount to 1 (instead of the default 2 as we are not that hungry). At line 8 we actually eat the fruit.

2.3 Visibility

So far, all we have is a class which is not object oriented. In object oriented programming, you would have each variable and function set to different visibility which would control how you would use them.

What I'm talking about is the following keywords you would use to start declaring the class's functions and variables.

  • public
  • private
  • protected
    The following quote made by genux does a pretty good job describing the keywords.

  • Private

    * Your privates are what you have.
    
  • Public

    * Anybody can touch them.
    
  • Protected

    * They are protected from the general public, but the inherited could touch them.
    

In order to use them you would use one of them in place of var when declaring class variables in the beginning. For instance, if we wanted to make the amount private (var would be the same as public, but not very good practice) we would write private instead of var.

class fruit
{

    private $amount = 2;

    public function eat()
    {
        // Chew
    }

}

If it's set to private, then we won't be able to use that class variable outside of the class. It's class's private variable and nobody else (no other class or function outside of this class) can touch it. This means, in order to set a different amount (rather then the default amount of 2) we would now need to do that within a function instead of directly. (The following would not work anymore).

$product->amount = 1;

Instead, now we need to define a function in the class that would enable us to change the amount in case we aren't hungry enough to eat 2 (or so hungry that 2 is not enough). Let's do that.

class fruit
{

    private $amount = 2;

    public function eat()
    {
        // Chew
    }

    public function amount($number)
    {
        $this->amount = $number;
    }

}

Here is where I would like to point out a few things. First of all, notice how I added the keyword public to the function. What that does is unlike the class variable amount I am able to use the function outside of the class. But I can use the private variable $amount in that public function, I just can't access the variable or modify it from outside of the class like I can access the function.

Another thing I want to point your attention to here is the usage of the class variable within the class. Since the function amount() is inside the class, that means I can access it outside of the class. And since the function amount() and the class variable $amount are inside the class, you could use the class variable $amount in the public function amount().

Reason we would want to do something like this is if we would need to do some checks on the variable and only way to do checks on a variable before setting to the variable, we would need to set that variable through a function. If we set a different number to $amount outside of the class, we are bypassing the checks.

Also notice the way the class variable was accessed in the class. It is important to understand this since this is how you would be accessing all of your class variables and functions from within the class. Instead of initiating the class object and using the class variable like that like we do when we are outside of the class, from within, we already have a variable that already holds the object. That variable is $this. We don't need to initiate it, as it is automatically initiated by the PHP engine/parser.

Let's say we wanted to do a reality check to the variable $amount to make sure we don't put a ridiculously large number in there that we wouldn't be able to eat. Let's say that we won't be able to eat more then 10 in a sitting no matter how hungry you were... so lets change the public function amount() to reflect that.

public function amount($number)
{
    if($number < 11)
    {
        $this->amount = $number;
    }
}

Now we have that check going (if $number is less then 11 then change the number) otherwise, if we put in 11 or more (or a generated number by the system) we would still have the default 2 (or if you previously put something, we would have that number instead).

3.0 Conclusion

In this part of the tutorial, you learned how to set-up a basic class, fill it with functions and variables and edit visibility of the the functions and variables. You learned how each visibility behaves and how it controls the class members.

This topic is pretty big and I'm not able to fit everything under one roof, so we're going to have to break this tutorial in to parts.

This page was published on It was last revised on

0

14 Comments

  • Votes
  • Oldest
  • Latest
Commented
Updated

While I agree part in with what you have said I would like to add a few things here.

You haven't used any access levels (private public etc). This kinda forms the bases for classes, the ability to wrap and only expose as is needed. I think that knowing classes is effectively the last thing you need to know in terms of OOP, why not do a tutorial on OOP then bring in the classes 🙂 (Just a suggestion, not being cocky)

One last thing. Your tutorial on types on the other site you are asked about the $i++ and ++$i. It has nothing to do with speed. The ++$i will increment before the context of the function/operation is complete and the $i++ will only increment i after the operation is complete.

try it

$j = 0;
$k = 0;
for($i = 0; $i < 10; $i++){
 echo "Line post:" . $j++ . "<br />";
 echo "Line pre:" . ++$k . "<br />";
}

You will notice that $k gets to 10 where as $j only gets to 9 🙂

add a comment
0
BO
433 9
Commented
Updated

Yeah... I know it has nothing to do with speed... I was told that it is faster in C/C++ (But I don't know those languages so I can't confirm that).

I didn't really think to bring that example up, but it is good that you have brought it up. I guess it is better when two people write a tutorial rather than one person writing a tutorial... makes the tutorial that much better 😁

Thanks for the advice as to tutorial order... didn't think about that one. I'll certainly start an OOP tutorial and the class access levels (private, public...)

Thanks for the feedback... lets me improve on my tutorials and knowledge as well (As I write tutorials 👍 )

add a comment
0
Commented
Updated

Only a pleasure, I admire the time you have put into all the tutorials 🙂

add a comment
0
BO
433 9
Commented
Updated

Thanks 🙂 Glad to know I'm not wasting my time 🤣

add a comment
0
SP
106 4
Commented
Updated

The reason ++i is "faster" than i++ in unmanaged languages such as C++ is that i++ requires an extra step.

Given the code:

int i = 5;
int val = ++i;

The program has to perform the following steps:

  1. Increment the value of i
  2. Set the value of val to that of i

But in the following code:

int i = 5;
int val = i++;

The program must perform an extra step:

  1. Copy the value of i to a temporary location
  2. Increment the value of i
  3. Set the value of val to the temporary value
add a comment
0
BO
433 9
Commented
Updated

That makes sense... thanks for pointing that out 🙂

add a comment
0
Commented
Updated

Why aren't you using PHP 5's superior syntax and capabilities? PHP 4 isn't even supported by Zend any longer, and PHP 5 has been around for, what, 5 or 6 years already?

add a comment
0
BO
433 9
Commented
Updated

What are you talking about?

add a comment
0
Commented
Updated

What are you talking about?

This:

class example
{
   var $name;
   var $last;
}

Is PHP 4 syntax. The keyword 'var' exists only to maintain backwards compatibility with legacy apps, and really shouldn't be used in modern apps as it's the same as declaring a data member public, which is a bad thing to do in most cases. So, like I asked earlier, why did you write a tutorial essentially using the syntax of a version of PHP that isn't even supported by Zend any longer if the current standard is:

  1. 5+ years old.
  2. Available virtually everywhere because of its age and overall benefits.
  3. The best way to go from a technical standpoint (PHP 5+ actually has member visibility modifiers, abstract classes and methods, interfaces, etc).

It just strikes me as odd that you'd write a tutorial that essentially starts someone down the path of PHP 4, and then say at the end "I'll explain how to do it the right way in another tutorial."

add a comment
0
Commented
Updated

HAHAHAHAHAHAHA like all the fancy new keywords in PHP 5 make ANY DIFFERENCE!

LOL it was a good attempt (PHP 5) to make it look like proper language. Besides, the title is understanding classes, not understanding OOP. The things you are talking about are intrinsic to OOP

add a comment
0
Commented
Updated

of course a class setup , in PHP 5 has the normal sort of cool things that OOP has..

private
public
and protected

the differences are.. or a good way to remember is

private = your privates are what you have!!!
public = anybody can touch them !! .. arhh run!!!
protected = they are protected from the general public.. but your inherited people can still touch them!!..

add a comment
0
Commented
Updated

Thanks Bogey. Finally understand this hahaha, from your short tutorial, after trying to find a way to understand this from the PHP manual (and elsewhere) for a while, your tutorial cleared everything up. Most sources just explain it horribly. Leaving important things out.

add a comment
0
BO
433 9
Commented
Updated

The tutorial has being redone to include more information and in an attempt to do a better job at teaching classes and OOP. Enjoy! 😁 (The second part of the tutorial is in the process of being written).

add a comment
0