Simply Cutting Edge
Welcome Guest [Log In] [Register]
Welcome to zetaNetwork. We hope you enjoy your visit.

You're currently viewing our forum as a guest. This means you are limited to certain areas of the board and there are some features you can't use. If you join our community, you'll be able to access member-only sections, and use many member-only features such as viewing zetaNetwork exclusive tutorials and articles, and access to our code snippets section. Registration is simple, fast, and completely free.


Click Here To Register


If you're already a member please log in to your account to access all of our features:

Username:   Password:
Add Reply
OOP For Noobs - Part 1
Topic Started: May 26 2011, 07:10 PM (186,557 Views)
Pro
Member Avatar
Underground Coding

OOP For Noobs - Part 1
Time: 1 Hour 30 Minutes
Difficulty: Medium



Note: This tutorial is for those of you who have at least a basic knowledge of PHP and wish to improve your code and your workflow. OOP in PHP is available in PHP5 only.

If you're one of those people who still use procedural, wow. Anyway, OOP or Object Oriented Programming is probably one of the best things in programming, the fact that it even came to PHP is like heaven on Earth. OOP is more than just learning new syntax however, it's a concept of programming that may be difficult to grasp at first but very powerful once you get used to it. For those of you who don't know what procedural looks like:
Code: PHP
 
$name1 = 'Bob';
$gender1 = 'Male';
$name2 = 'Sally';
$gender2 = 'Female';

echo $name1, ' Is A ', $gender1;
echo $name2, ' Is A ', $gender2;
That's procedural ;) bogging down your applications with loads of variables and other stuff you don't need. Using objects helps keep your neat and organized. Not to mention, you can have your own type of variables, well sorta. This tutorial will consist of 7 parts:

  • Objects and Classes
  • Interfaces and Abstract Classes
  • PDO
  • Forum Demo Project - Forum List View
  • Forum Demo Project - Topic List View
  • Forum Demo Project - Topic View
  • Forum Demo Project - Posting
If you look at our to do list you'll see that we will be making a forum. We could make a bunch of variables for each forum but that would be too cluttered and disorganized, we could even use arrays, but that would still be a bit disorganized. Instead we're gonna use objects to create a new type of variable, a forum variable, topic variable, and post variable. Wait what? I thought you could only have stuff like integers, strings, characters, and floats. Well an object is similar to a type of variable, however it's not a type of variable at all. I'll show you what I mean.
Code: PHP
 
<?php
class Forum{
private $name;

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

public function get_name(){
return $this->name;
}
}

$forum1 = new Forum('ITS OVER 9000');
$forum2 = new Forum('ITS NOT OVER 9000');
echo $forum1->get_name(), '<br />';
echo $forum2->get_name();
?>
That block of code looks scary right? Well it's not :P we'll be breaking it down line by line so don't worry, but first, let's go over what an object is: An object is basically a form of a class (see below). Each object is unique and holds it's own attributes and functions. Now let's get started cracking down on that block of code.

Code: PHP
 
<?php
You should know what that means.
Code: PHP
 
class Forum{
That line declares a new class. What's a class? A class is basically a blueprint for your object. Think about a class as a blueprint for a house. A house has various attributes, such as size, color, etc. A house also has various functions such as allowing you to live in it. An object is just like a house. It can have attributes and functions, plus it can even have a constructor which is like building your house, or object in this case. In this case, our class name is Forum.
Code: PHP
 
private $name;
$name is an attribute of our Forum class. Attributes can basically be anything a variable can be, integers, strings, reference variables. See "private"? The word private is a visibility modifier. Visibility modifiers basically tell your application what can access that specific attribute/function and what can't. A list of visibility modifiers are as follows:

  • public - This means that anything can access this attribute/function. Even things outside the class.
  • private - This means only functions and attributes from within the class itself can access it.
  • protected - This means only functions and attributes from within the class and any subclasses can access it.

Here's a nice table if you need them in more detail:

Access WithPublicPrivateProtected
Within The Same ClassYesYesYes
Outside The ClassYes NoNo
SubclassesYesNoYes

Note: Class attributes and functions are public unless specified otherwise.

These visibility modifiers also allow for encapsulation. What's encapsulation? Encapsulation is basically when only things relevant to the current object are accessible to the object. If you had for example a human object. You don't want to know how the human walks, talks, eats, or sings. You just want the human to walk, talk, etc. Encapsulation makes it so you don't need to know how something works, you just want it to work.
Code: PHP
 
function __construct($name){
$this->name = $name;
}
What's this, a function with two underscores before it? This is the constructor, think of it as the order to create a new house. It sets everything that is needed in the object, instance variables, etc. It essentially, contains code that needs to be executed when an object is created. The constructor is automatically called on the creation of a new object and is always public.
Code: PHP
 
$this->name = $name;
A lot of people seem to get confused by this so I'm going to go over this in depth. $this refers to the current object instance. The arrow refers to something inside the current object, in this case the name variable. Note how you don't need a $ after name. Then you see = $name, this means that the name attribute of our object is being set to $name, which is passed through our constructor.

Wait, did we just set the name attribute of our attribute to itself? No, we did not. $this->name refers to the name attribute in our class. $name refers to the string that was passed in our constructor.

Wait, what's an instance? An instance is basically another name for an object. Each Forum object basically has it's own personal name attribute, unless $name is declared static. By putting the word static in between private and $name, $name will have the same value across all forum objects. Meaning if you change the value of name for one Forum object you change the value of name for all instances of Forum. To access a static attribute or function from within an object use self::your_attribute_or_function().
Code: PHP
 
public function get_name(){
return $this->name;
}
That line of code basically say, create a new function called get_name that is accessible by everything. The function will return the name attribute of our object.

Add in one more closing bracket and we're done with our class. Now let's move on to the next part of the code, which creates two Forum objects.
Code:
 
$forum1 = new Forum('ITS OVER 9000');
Create a new variable called forum1, forum1 will be a reference variable to a new Forum object. Notice how we passed a forum name to our constructor. This sets the name of our Forum object to "IT'S OVER 9000". Do the same thing with $forum2 except with a different name and there you have it, two forum objects. Now let's print the names of our forums.
Code: PHP
 
echo $forum1->get_name(), '<br />';
echo $forum2->get_name();
Echo the string that is returned by get_name() and there you have it. We've gone through all the code in our sample. Now let's get a bit more in depth with OOP now that we've gone over the basics.

Recall how I mentioned subclasses with visibility modifiers. What's a subclass, a subclass is basically a class that inherits all the public and protected attributes and functions of it's parent class.

What's inheritance? Inheritance is one of those concepts and parts of OOP that helps you save time maximizing efficiency. For example, say you had a Computer class, a Desktop class, and a Laptop class. Without inheritance you would have to define an attribute, such as processor in every single class. Inheritance helps us save time by allowing a class to be a subclass of another class meaning you only need to declare the processor attribute as public or protected in the parent class and all subclasses of that class will have the attribute processor. It is due to inheritance that people will usually create a very generic class containing attributes and functions that multiple classes will use and create subclasses of that class gradually getting more and more specific with their classes.

Note: Everything, even the constructor can be inherited.

Here's some sample code to show you how to use inheritance.
Code:
 
<?php
class Computer{
protected $processor;
protected $storage;
protected $os;

public function __construct($proessor, $storage, $os){
$this->processor = $proessor;
$this->storage = $storage;
$this->os = $os;
}

public function get_stats(){
$stats = '';
$stats .= $processor . ', ';
$stats .= $storage . ', ';
$stats .= $os . ', ';

return $stats;
}
}

class Laptop extends Computer{
private $battery;

public function __construct($battery, $processor, $storage, $os){
parent::__construct($processor, $storage, $os);
$this->battery = $battery;
}

public function get_stats(){
$stats = '';
$stats .= $this->battery . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Laptop';

return $stats;
}
}

class Desktop extends Computer{
private $size;

public function __construct($size, $processor, $storage, $os){
parent::__construct($processor, $storage, $os);
$this->size = $size;
}

public function get_stats(){
$stats = '';
$stats .= $this->size . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Desktop';

return $stats;
}
}

$laptop = new Laptop('2 Hours', '2.7 GHZ', '1 TB', 'Windows 7');
$desktop = new Desktop('50 LB', '3.5 GHZ', '1 TB', 'Mac OSX');

echo $laptop->get_stats(), '<br />';
echo $desktop->get_stats();
?>
Whoa, that's a large block of code. Let's take it easy, class by class, line by line.
Code: PHP
 
class Laptop extends Computer{
private $battery;

public function __construct($battery, $processor, $storage, $os){
parent::__construct($processor, $storage, $os);
$this->battery = $battery;
}

public function get_stats(){
$stats = '';
$stats .= $this->battery . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Laptop';

return $stats;
}
}
We'll start with the Computer class which contains three protected attributes and a constructor.
Code: PHP
 
protected $processor;
protected $storage;
protected $os;
Our Computer class will hold the protected variables processor, storage, and os. All of them will be set from within the constructor.
Code: PHP
 
public __construct($processor, $storage, $os){
$this->processor = $processor;
$this->storage = $storage;
$this->os = $os;
}
Within our constructor we set our class attributes to their corresponding values.
Code: PHP
 
public function get_stats(){
$stats = '';
$stats .= $this->battery . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Laptop';

return $stats;
}

We'll also declare a get_stats function that returns the stats of our computer.

Now for the good stuff :)
Code: PHP
 
class Laptop extends Computer{
private $battery;

public function __construct($battery, $processor, $storage, $os){
parent::__construct($processor, $storage, $os);
$this->battery = $battery;
}

public function get_stats(){
$stats = '';
$stats .= $this->battery . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Laptop';

return $stats;
}
}
You're probably looking at this code and thinking, "What the hell does it do?" Well for starters look at the class heading, "extends Computer", that means that this class, Laptop, is a subclass of computer. All the public and protected attributes and functions are inherited by Laptop.

"But if it's inherited why do you need to redeclare the constructor and get_stats?" You may need to redeclare the constructor, because Laptop is a different class, but you don't need to redefine get_stats. The reason we are redefining it, though, is because the get_stats function in our Computer class doesn't print out the battery attribute in our Laptop class. By defining get_stats in our Laptop class we are overriding the get_stats function in Computer and therefore $this->get_stats() will call the get_stats function from Laptop and not Computer.
Code: PHP
 
public function __construct($battery, $processor, $storage, $os){
parent::__construct($processor, $storage, $os);
$this->battery = $battery;
}
You already know what the constructor header does and what $this->battery = $battery does. Now we're gonna go over what "parent::" does. The keyword parent means the parent of our Laptop class, in this case, Computer. The line "parent::__construct(...);" means that we are calling the constructor of our parent class. Yep, that's right, the constructor of a parent class is not automatically called when a child class, or subclass, is instantiated.
Code: PHP
 
public function get_stats(){
$stats = '';
$stats .= $this->size . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Desktop';

return $stats;
}
Wait, the class attributes processor, storage, and os were not defined in our class!!! Actually, they were, when we extended our class our class inherited all the attributes of Computer, including processor, storage, and os.

The same thing goes for our Desktop class.
Code: PHP
 
class Desktop extends Computer{
private $size;

public function __construct($size, $processor, $storage, $os){
parent::__construct($processor, $storage, $os);
$this->size = $size;
}

public function get_stats(){
$stats = '';
$stats .= $this->size . ', ';
$stats .= $this->processor . ', ';
$stats .= $this->storage . ', ';
$stats .= $this->os . ', Desktop';

return $stats;
}
}


Well there you have it, part 1 of OOP For Noobs. I know, long right? In the next part of this tutorial series we'll be going over abstract classes and interfaces. If you have any questions or comments post them here and remember, you can always download the source files in the attachment below.
Attached to this post:
Attachments: oop_part_1.zip (799 Bytes)
Pro | zetaNetwork Instructor & Admin
I Coded Most Of The Smexy Stuff You See :P
PM Me Any Questions
Need live support? Click here.
Offline Profile Quote ^
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Tutorials · Next Topic »
Add Reply