Forum rules

Please read our Guide to Making Ozzu Tutorials if you would like to submit your own tutorials.

Understanding Classes

  • Bogey
  • PHP Ninja
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 7337
  • Loc: Imagination
  • Status: Offline

Post July 15th, 2009, 12:14 pm

Understanding Classes

Introduction


This is an introductory tutorial to classes and OOP (Object Oriented Programming) in PHP; for those who know the basics of the PHP language.

Classes are really extraordinary and allow you code powerful programs if you use them well. This forum is generally based on classes and a group of functions

Skeleton of a class


Classes are really easy to use actually and nothing to be afraid of. I used to shy away from them before I started using them, but when I started to learn classes, I was suprised and I understood I overestimated it.

You can name a class with anything you want. The class names could be made with letters, numbers, and underlines "_". Remember, that if you use numbers in the class name, it cannot be the first character, you need to have a letter be the first character. You tell the PHP parser that it is a class by putting the word 'class ' in front of the class name.

Below is an example of a simple small class:
PHP Code: [ Download ] [ Select ]
<?php
class abc123_class {
    var $var = false;
   
    function func_test()
    {
        // Function test
    }
}
?>
  1. <?php
  2. class abc123_class {
  3.     var $var = false;
  4.    
  5.     function func_test()
  6.     {
  7.         // Function test
  8.     }
  9. }
  10. ?>

Don't worry if you don't understand all of that right now, I would explain all of that later in this tutorial.

What is so good about a class, is that you could pass variables between functions without having to make them global or passing the variable into the argument of the function. It is also possible to share variables and function between classes, and I would talk about this later as it's big enough for a whole different tutorial :)

The variables within the class that could be passed between function to function that are inside of a class are accessible with the '$this' keyword. It is recommended that you pre-define them before you use them to avoid getting errors like "such and such variable not defined", and to just create default values to those variables.

Below is an example class using the variable thing.

PHP Code: [ Download ] [ Select ]
<?php
class example {
    var $name = false;
    var $last = false;
   
    function name($first, $last)
    {
        $this->name = $first;
        $this->last = $last;
    }
   
    function show()
    {
        echo $this->name . ' ' . $this->last;
    }
}
?>
  1. <?php
  2. class example {
  3.     var $name = false;
  4.     var $last = false;
  5.    
  6.     function name($first, $last)
  7.     {
  8.         $this->name = $first;
  9.         $this->last = $last;
  10.     }
  11.    
  12.     function show()
  13.     {
  14.         echo $this->name . ' ' . $this->last;
  15.     }
  16. }
  17. ?>

I used string concatenation there to show that you could do that with class-wide variables like you would with normal classes. Basically,they are normal variables and could be used as such... as an array, boolean, intager, float, etc. etc., they just have a clas-wide scope and are accessible by the keyword '$this'. Don't get that confused :)

The keyword '$this' could only be used within a method that is inside of an object... in this case, inside of a function that is inside of a class. You can't have the keyword outside of a function and inside of a class as that gives you an error.

You can have as many variables, as many functions inside of a class as you want/need for your system/script, there is no limit.

Using Classes


To use an object/class, you need to create a new instance of the object and set it to a variable named however you like. Classes should be defined before they could be initiated. Below is an example of initiating a class:
PHP Code: [ Download ] [ Select ]
<?php
$object_res = new example();
?>
  1. <?php
  2. $object_res = new example();
  3. ?>

Using the functions and variables inside of that class/object, isn't difficult, you use the arrow ( -> ) like you do to access class-wide variables with the keyword '$this'. Below is an example:
PHP Code: [ Download ] [ Select ]
<?php
$object_res = new example();
 
$object_res->name = 'Mark';
$object_res->last = 'Jones';
 
$object_res->show();
?>
  1. <?php
  2. $object_res = new example();
  3.  
  4. $object_res->name = 'Mark';
  5. $object_res->last = 'Jones';
  6.  
  7. $object_res->show();
  8. ?>

The above code example would print "Mark Jones" becuase the function show() is defined to echo the first name and the last name.

There are many types of variables formally known as 'Data Types' and this one is 'object'. You can read more on datatypes here to understand more on a few of them and to get a list of all data types.

A Few Warnings


If you are going to use classes after this tutorial and you don't know any more abou the classes, I wouldn't suggest naming any function the same as your class name. It is possible, and in most cases a good idea to do that, but I haven't covered that in this tutorial and will in a later tutorial.

What it's called though is a magic method and is equivalent to __construct, but again, I would talk about all this at a later tutorial,so bare with me here :D

What you can do


What you can do to reinforce your learning experience is practice writing classes with variables talking between functions within a class. The first thing I done in a class is a database access wrapper... I had a function to connect to the database, and a function to select and that stuff... right now, the completed class could be found on PHP-Classes repository.

Conclusion


Hopefully you learned the basics of classes and ready to go to the more advanced stuff once the tutorial comes out here.
Learn PHP

Apocalyptica - I Don't Care (Listen to this most awesome song ever!)
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post July 15th, 2009, 12:14 pm

  • Rabid Dog
  • Cheese Monkey
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3188
  • Loc: South Africa
  • Status: Offline

Post August 7th, 2009, 8:54 am

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: [ Download ] [ 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 :)
My Software Development Company
Music I have recorded (fixed now :))
Image
  • Bogey
  • PHP Ninja
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 7337
  • Loc: Imagination
  • Status: Offline

Post August 7th, 2009, 11:35 pm

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: )
Learn PHP

Apocalyptica - I Don't Care (Listen to this most awesome song ever!)
  • Rabid Dog
  • Cheese Monkey
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3188
  • Loc: South Africa
  • Status: Offline

Post August 8th, 2009, 4:46 am

Only a pleasure, I admire the time you have put into all the tutorials :)
My Software Development Company
Music I have recorded (fixed now :))
Image
  • Bogey
  • PHP Ninja
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 7337
  • Loc: Imagination
  • Status: Offline

Post August 8th, 2009, 11:39 am

Thanks :) Glad to know I'm not wasting my time :lol:
Learn PHP

Apocalyptica - I Don't Care (Listen to this most awesome song ever!)
  • spork
  • \x -> x `mod` o
  • Silver Member
  • User avatar
  • Joined: Sep 22, 2003
  • Posts: 5616
  • Loc: Rochester, NY
  • Status: Offline

Post August 8th, 2009, 5:19 pm

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

Given the code:

Code: [ Download ] [ 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: [ Download ] [ 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
Working on writing myself a Scheme
me
  • Bogey
  • PHP Ninja
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 7337
  • Loc: Imagination
  • Status: Offline

Post August 8th, 2009, 5:23 pm

That makes sense... thanks for pointing that out :)
Learn PHP

Apocalyptica - I Don't Care (Listen to this most awesome song ever!)
  • Nightslyr
  • Proficient
  • Proficient
  • No Avatar
  • Joined: Sep 21, 2005
  • Posts: 256
  • Status: Offline

Post November 18th, 2009, 2:03 pm

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
  • PHP Ninja
  • Genius
  • User avatar
  • Joined: Jul 14, 2005
  • Posts: 7337
  • Loc: Imagination
  • Status: Offline

Post November 18th, 2009, 7:23 pm

What are you talking about?
Learn PHP

Apocalyptica - I Don't Care (Listen to this most awesome song ever!)
  • Nightslyr
  • Proficient
  • Proficient
  • No Avatar
  • Joined: Sep 21, 2005
  • Posts: 256
  • Status: Offline

Post November 19th, 2009, 5:54 am

Bogey wrote:
What are you talking about?


This:

PHP Code: [ Download ] [ 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
  • Cheese Monkey
  • Web Master
  • User avatar
  • Joined: May 21, 2004
  • Posts: 3188
  • Loc: South Africa
  • Status: Offline

Post November 19th, 2009, 9:27 am

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
My Software Development Company
Music I have recorded (fixed now :))
Image
  • genux
  • Graduate
  • Graduate
  • User avatar
  • Joined: Jan 22, 2010
  • Posts: 101
  • Loc: UK
  • Status: Offline

Post January 22nd, 2010, 3:42 am

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

Post Information

  • Total Posts in this topic: 12 posts
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 3 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
 
 

© 2010 Unmelted, LLC. Driven by phpBB © 2010 phpBB Group.