Classes and OOP (Part 1)

  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8388
  • Loc: USA

Post 3+ Months Ago

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:
PHP Code: [ Select ]
// Initiating the class (making an object)
$object = new class();
 
// Accessing the class's function
$object->classFunction();
 
// Accessing the class's variable
$object->classVariable;
 
  1. // Initiating the class (making an object)
  2. $object = new class();
  3.  
  4. // Accessing the class's function
  5. $object->classFunction();
  6.  
  7. // Accessing the class's variable
  8. $object->classVariable;
  9.  


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:
PHP Code: [ Select ]
class fruit
{
 
}
  1. class fruit
  2. {
  3.  
  4. }

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.
PHP Code: [ Select ]
class fruit
{
 
    function eat()
    {
        // Chew
    }
   
}
  1. class fruit
  2. {
  3.  
  4.     function eat()
  5.     {
  6.         // Chew
  7.     }
  8.    
  9. }

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).

PHP Code: [ Select ]
class fruit {
 
    function eat() {
        // Chew
    }
   
}
  1. class fruit {
  2.  
  3.     function eat() {
  4.         // Chew
  5.     }
  6.    
  7. }


So far, we have only added a function, now let's add a variable.
PHP Code: [ Select ]
class fruit
{
 
    var $amount;
 
    function eat()
    {
        // Chew
    }
   
}
  1. class fruit
  2. {
  3.  
  4.     var $amount;
  5.  
  6.     function eat()
  7.     {
  8.         // Chew
  9.     }
  10.    
  11. }

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).
PHP Code: [ Select ]
class fruit
{
 
    var $amount = 2;
 
    function eat()
    {
        // Chew
    }
   
}
  1. class fruit
  2. {
  3.  
  4.     var $amount = 2;
  5.  
  6.     function eat()
  7.     {
  8.         // Chew
  9.     }
  10.    
  11. }

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.
PHP Code: [ Select ]
// Initiating the class (making an object)
$product = new fruit();
 
// Setting the amount of fruit
$product->amount = 1;
 
// Eating the fruit
$product->eat();
 
  1. // Initiating the class (making an object)
  2. $product = new fruit();
  3.  
  4. // Setting the amount of fruit
  5. $product->amount = 1;
  6.  
  7. // Eating the fruit
  8. $product->eat();
  9.  

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.
PHP Code: [ Select ]
class fruit
{
 
    private $amount = 2;
 
    public function eat()
    {
        // Chew
    }
   
}
  1. class fruit
  2. {
  3.  
  4.     private $amount = 2;
  5.  
  6.     public function eat()
  7.     {
  8.         // Chew
  9.     }
  10.    
  11. }

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).
PHP Code: [ Select ]
$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.
PHP Code: [ Select ]
class fruit
{
 
    private $amount = 2;
 
    public function eat()
    {
        // Chew
    }
   
    public function amount($number)
    {
        $this->amount = $number;
    }
   
}
  1. class fruit
  2. {
  3.  
  4.     private $amount = 2;
  5.  
  6.     public function eat()
  7.     {
  8.         // Chew
  9.     }
  10.    
  11.     public function amount($number)
  12.     {
  13.         $this->amount = $number;
  14.     }
  15.    
  16. }

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.
PHP Code: [ Select ]
public function amount($number)
{
    if($number < 11)
    {
        $this->amount = $number;
    }
}
  1. public function amount($number)
  2. {
  3.     if($number < 11)
  4.     {
  5.         $this->amount = $number;
  6.     }
  7. }

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.
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

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
Code: [ Select ]
$j = 0;
$k = 0;
for($i = 0; $i < 10; $i++){
echo "Line post:" . $j++ . "<br />";
echo "Line pre:" . ++$k . "<br />";
}
  1. $j = 0;
  2. $k = 0;
  3. for($i = 0; $i < 10; $i++){
  4. echo "Line post:" . $j++ . "<br />";
  5. echo "Line pre:" . ++$k . "<br />";
  6. }


You will notice that $k gets to 10 where as $j only gets to 9 :)
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8388
  • Loc: USA

Post 3+ Months Ago

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 :D

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 :thumbsup: )
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Only a pleasure, I admire the time you have put into all the tutorials :)
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8388
  • Loc: USA

Post 3+ Months Ago

Thanks :) Glad to know I'm not wasting my time :lol:
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6245
  • Loc: Seattle, WA

Post 3+ Months Ago

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

Given the code:

Code: [ Select ]
int i = 5;
int val = ++i;
  1. int i = 5;
  2. 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:

Code: [ Select ]
int i = 5;
int val = i++;
  1. int i = 5;
  2. 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
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8388
  • Loc: USA

Post 3+ Months Ago

That makes sense... thanks for pointing that out :)
  • Nightslyr
  • Proficient
  • Proficient
  • Nightslyr
  • Posts: 283

Post 3+ Months Ago

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?
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8388
  • Loc: USA

Post 3+ Months Ago

What are you talking about?
  • Nightslyr
  • Proficient
  • Proficient
  • Nightslyr
  • Posts: 283

Post 3+ Months Ago

Bogey wrote:
What are you talking about?


This:

PHP Code: [ Select ]
class example
{
   var $name;
   var $last;
}
  1. class example
  2. {
  3.    var $name;
  4.    var $last;
  5. }


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."
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

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
  • genux
  • Graduate
  • Graduate
  • User avatar
  • Posts: 106
  • Loc: UK

Post 3+ Months Ago

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!!..
  • Kurthead+1
  • Graduate
  • Graduate
  • Kurthead+1
  • Posts: 130

Post 3+ Months Ago

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.
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8388
  • Loc: USA

Post 3+ Months Ago

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

Post Information

  • Total Posts in this topic: 15 posts
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 2 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.