object-oriented php for beginners - tuts+ code tutorial

44
Get a Tuts+ subscription for just $45! Deploy New Relic now to claim. Dismiss Categories Learning Guides Code For many PHP programmers, objectoriented programming is a frightening concept, full of complicated syntax and other roadblocks. As detailed in my book, Pro PHP and jQuery, you'll learn the concepts behind objectoriented programming (OOP), a style of coding in which related actions are grouped into classes to aid in creating morecompact, effective code. Understanding ObjectOriented Programming Objectoriented programming is a style of coding that allows developers to group similar tasks into classes. This helps keep code following the tenet "don't repeat yourself" (DRY) and easytomaintain. "Objectoriented programming is a style of coding that allows developers to group similar tasks into classes." One of the major benefits of DRY programming is that, if a piece of information changes in your program, usually only one change is required to update the code. One of the biggest nightmares for developers is maintaining code where data is declared over and over again, meaning any changes to the program become an infinitely more frustrating game of Where's Waldo? as they hunt for duplicated data and functionality. BACKEND ObjectOriented PHP for Beginners by Jason Lengstorf 23 Dec 2011 625 Comments English 319 73 458

Upload: md-aman-ullah

Post on 22-Dec-2015

52 views

Category:

Documents


13 download

DESCRIPTION

Object-Oriented PHP for Beginners - Tuts+ Code Tutorial read to know about OOP in Php

TRANSCRIPT

Page 1: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 1/44

Get a Tuts+ subscription for just $45!Deploy New Relic now to claim.

Dismiss

Categories Learning Guides

Code

For many PHP programmers, objectoriented programming is a frightening concept,full of complicated syntax and other roadblocks. As detailed in my book, Pro PHPand jQuery, you'll learn the concepts behind objectoriented programming (OOP),a style of coding in which related actions are grouped into classes to aid in creatingmorecompact, effective code.

Understanding ObjectOriented Programming

Objectoriented programming is a style of coding that allows developers to groupsimilar tasks into classes. This helps keep code following the tenet "don't repeatyourself" (DRY) and easytomaintain.

"Objectoriented programming is a style of coding thatallows developers to group similar tasks into classes."

One of the major benefits of DRY programming is that, if a piece of informationchanges in your program, usually only one change is required to update thecode. One of the biggest nightmares for developers is maintaining code where datais declared over and over again, meaning any changes to the program become aninfinitely more frustrating game of Where's Waldo? as they hunt for duplicated data

and functionality.

BACKEND

ObjectOriented PHP forBeginnersby Jason Lengstorf 23 Dec 2011 625 Comments English

319 73 458

Page 2: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 2/44

and functionality.

OOP is intimidating to a lot of developers because it introduces new syntax and, at aglance, appears to be far more complex than simple procedural, or inline, code.However, upon closer inspection, OOP is actually a very straightforward andultimately simpler approach to programming.

Understanding Objects and Classes

Before you can get too deep into the finer points of OOP, a basic understanding ofthe differences between objects and classes is necessary. This section will go overthe building blocks of classes, their different capabilities, and some of their uses.

Recognizing the Differences Between Objects and Classes

Photos by Instant Jefferson and John Wardell

Developers start talking about objects and classes, andthey appear to be interchangeable terms. This is not thecase, however.

Right off the bat, there's confusion in OOP: seasoned developers start talking aboutobjects and classes, and they appear to be interchangeable terms. This is not the

case, however, though the difference can be tough to wrap your head around at first.

Page 3: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 3/44

case, however, though the difference can be tough to wrap your head around at first.

A class, for example, is like a blueprint for a house. It defines the shape of thehouse on paper, with relationships between the different parts of the house clearlydefined and planned out, even though the house doesn't exist.

An object, then, is like the actual house built according to that blueprint. The datastored in the object is like the wood, wires, and concrete that compose the house:without being assembled according to the blueprint, it's just a pile of stuff. However,when it all comes together, it becomes an organized, useful house.

Classes form the structure of data and actions and use that information tobuild objects. More than one object can be built from the same class at the sametime, each one independent of the others. Continuing with our construction analogy,it's similar to the way an entire subdivision can be built from the same blueprint: 150different houses that all look the same but have differentfamilies and decorations inside.

Structuring ClassesThe syntax to create a class is pretty straightforward: declare a class using theclass keyword, followed by the name of the class and a set of curly braces ( ):

After creating the class, a new class can be instantiated and stored in a variableusing the new keyword:

To see the contents of the class, use var_dump() :

12345678

<?php class MyClass // Class properties and methods go here ?>

1 $obj = new MyClass;

Page 4: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 4/44

Try out this process by putting all the preceding code in a new file called test.phpin [your local] testing folder:

Load the page in your browser at http://localhost/test.php and the followingshould display:

In its simplest form, you've just completed your first OOP script.

Defining Class Properties

To add data to a class, properties, or classspecific variables, are used. These workexactly like regular variables, except they're bound to the object and therefore canonly be accessed using the object.

To add a property to MyClass , add the following code to your script:

1 var_dump($obj);

010203040506070809101112

<?php class MyClass // Class properties and methods go here $obj = new MyClass; var_dump($obj); ?>

1 object(MyClass)#1 (0)

0102030405060708

<?php class MyClass public $prop1 = "I'm a class property!";

$obj = new MyClass;

Page 5: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 5/44

The keyword public determines the visibility of the property, which you'll learnabout a little later in this chapter. Next, the property is named using standardvariable syntax, and a value is assigned (though class properties do not need aninitial value).

To read this property and output it to the browser, reference the object from which toread and the property to be read:

Because multiple instances of a class can exist, if the individual object is notreferenced, the script would be unable to determine which object to read from. Theuse of the arrow ( ‐> ) is an OOP construct that accesses the contained propertiesand methods of a given object.

Modify the script in test.php to read out the property rather than dumping thewhole class by modifying the code as shown:

Reloading your browser now outputs the following:

Defining Class Methods

0809101112

$obj = new MyClass; var_dump($obj); ?>

1 echo $obj‐>prop1;

010203040506070809101112

<?php class MyClass public $prop1 = "I'm a class property!"; $obj = new MyClass; echo $obj‐>prop1; // Output the property ?>

1 I'm a class property!

Page 6: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 6/44

Defining Class Methods

Methods are classspecific functions. Individual actions that an object will be able toperform are defined within the class as methods.

For instance, to create methods that would set and get the value of the classproperty $prop1 , add the following to your code:

Note — OOP allows objects to reference themselves using $this . When workingwithin a method, use $this in the same way you would use the object nameoutside the class.

To use these methods, call them just like regular functions, but first, reference theobject they belong to. Read the property from MyClass , change its value, and read itout again by making the modifications below:

01020304050607080910111213141516171819202122

<?php class MyClass public $prop1 = "I'm a class property!"; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; $obj = new MyClass; echo $obj‐>prop1; ?>

01020304

05

<?php class MyClass

public $prop1 = "I'm a class property!";

Page 7: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 7/44

Reload your browser, and you'll see the following:

"The power of OOP becomes apparent when usingmultiple instances of thesame class."

05060708091011121314151617181920212223242526

public $prop1 = "I'm a class property!"; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; $obj = new MyClass; echo $obj‐>getProperty(); // Get the property value $obj‐>setProperty("I'm a new property value!"); // Set a new one echo $obj‐>getProperty(); // Read it out again to show the change ?>

12

I'm a class property!I'm a new property value!

010203040506070809101112131415

16

<?php class MyClass public $prop1 = "I'm a class property!"; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />";

Page 8: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 8/44

When you load the results in your browser, they read as follows:

As you can see, OOP keeps objects as separate entities, which makes for easyseparation of different pieces of code into small, related bundles.

Magic Methods in OOP

To make the use of objects easier, PHP also provides a number of magic methods,or special methods that are called when certain common actions occur withinobjects. This allows developers to perform a number of useful tasks with relativeease.

Using Constructors and DestructorsWhen an object is instantiated, it's often desirable to set a few things right off the bat.To handle this, PHP provides the magic method __construct() , which is calledautomatically whenever a new object is

created.

16171819202122232425262728293031323334

// Create two objects$obj = new MyClass;$obj2 = new MyClass; // Get the value of $prop1 from both objectsecho $obj‐>getProperty();echo $obj2‐>getProperty(); // Set new values for both objects$obj‐>setProperty("I'm a new property value!");$obj2‐>setProperty("I belong to the second instance!"); // Output both objects' $prop1 valueecho $obj‐>getProperty();echo $obj2‐>getProperty(); ?>

1234

I'm a class property!I'm a class property!I'm a new property value!I belong to the second instance!

Page 9: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 9/44

created.

For the purpose of illustrating the concept of constructors, add a constructor toMyClass that will output a message whenever a new instance of the class iscreated:

Note — __CLASS__ returns the name of the class in which it is called; this is what isknown as a magic constant. There are several available magic constants, which youcan read more about in the PHP manual.

Reloading the file in your browser will produce the following result:

0102030405060708091011121314151617181920212223242526272829303132

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; // Create a new object$obj = new MyClass; // Get the value of $prop1echo $obj‐>getProperty(); // Output a message at the end of the fileecho "End of file.<br />"; ?>

Page 10: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 10/44

To call a function when the object is destroyed, the __destruct() magic method isavailable. This is useful for class cleanup (closing a database connection, forinstance).

Output a message when the object is destroyed by defining the magic method__destruct() in MyClass :

With a destructor defined, reloading the test file results in the following output:

123

The class "MyClass" was initiated!I'm a class property!End of file.

01020304050607080910111213141516171819202122232425262728293031323334353637

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; // Create a new object$obj = new MyClass; // Get the value of $prop1echo $obj‐>getProperty(); // Output a message at the end of the fileecho "End of file.<br />"; ?>

Page 11: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 11/44

With a destructor defined, reloading the test file results in the following output:

"When the end of a file is reached, PHP automaticallyreleases all resources."

To explicitly trigger the destructor, you can destroy the object using thefunction unset() :

1234

The class "MyClass" was initiated!I'm a class property!End of file.The class "MyClass" was destroyed.

01020304050607080910111213141516171819202122232425262728293031323334

35

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; // Create a new object$obj = new MyClass; // Get the value of $prop1echo $obj‐>getProperty(); // Destroy the object

unset($obj);

Page 12: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 12/44

Now the result changes to the following when loaded in your browser:

Converting to a StringTo avoid an error if a script attempts to output MyClass as a string, another magicmethod is used called __toString() .

Without __toString() , attempting to output the object as a string results in a fatalerror. Attempt to use echo to output the object without a magic method in place:

353637383940

unset($obj); // Output a message at the end of the fileecho "End of file.<br />"; ?>

1234

The class "MyClass" was initiated!I'm a class property!The class "MyClass" was destroyed.End of file.

010203040506070809101112131415161718192021222324

25

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />";

Page 13: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 13/44

This results in the following:

To avoid this error, add a __toString() method:

25262728293031323334353637383940

// Create a new object$obj = new MyClass; // Output the object as a stringecho $obj; // Destroy the objectunset($obj); // Output a message at the end of the fileecho "End of file.<br />"; ?>

123

The class "MyClass" was initiated! Catchable fatal error: Object of class MyClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 40

0102030405060708091011121314151617181920212223

24

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval)

Page 14: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 14/44

In this case, attempting to convert the object to a string results in a call to thegetProperty() method. Load the test script in your browser to see the result:

Tip — In addition to the magic methods discussed in this section, several others areavailable. For a complete list of magic methods, see the PHP manual page.

Using Class Inheritance

Classes can inherit the methods and properties of another class using theextends keyword. For instance, to create a second class that extends MyClass andadds a method, you would add the following to your test file:

2425262728293031323334353637383940414243444546

$this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; // Create a new object$obj = new MyClass; // Output the object as a stringecho $obj; // Destroy the objectunset($obj); // Output a message at the end of the fileecho "End of file.<br />"; ?>

1234

The class "MyClass" was initiated!Using the toString method: I'm a class property!The class "MyClass" was destroyed.End of file.

0102

03

<?php

class MyClass

Page 15: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 15/44

Upon reloading the test file in your browser, the following is output:

03040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051

class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; class MyOtherClass extends MyClass public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; // Create a new object$newobj = new MyOtherClass; // Output the object as a stringecho $newobj‐>newMethod(); // Use a method from the parent classecho $newobj‐>getProperty(); ?>

Page 16: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 16/44

Overwriting Inherited Properties and MethodsTo change the behavior of an existing property or method in the new class, you cansimply overwrite it by declaring it again in the new class:

1234

The class "MyClass" was initiated!From a new method in MyOtherClass.I'm a class property!The class "MyClass" was destroyed.

01020304050607080910111213141516171819202122232425262728293031323334353637383940

41

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; class MyOtherClass extends MyClass public function __construct() echo "A new constructor in " . __CLASS__ . ".<br />";

public function newMethod()

Page 17: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 17/44

This changes the output in the browser to:

Preserving Original Method Functionality While OverwritingMethodsTo add new functionality to an inherited method while keeping the original methodintact, use the parent keyword with the scope resolution operator ( :: ):

41424344454647484950515253545556

public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; // Create a new object$newobj = new MyOtherClass; // Output the object as a stringecho $newobj‐>newMethod(); // Use a method from the parent classecho $newobj‐>getProperty(); ?>

1234

A new constructor in MyOtherClass.From a new method in MyOtherClass.I'm a class property!The class "MyClass" was destroyed.

01020304050607080910111213141516171819

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString()

Page 18: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 18/44

This outputs the result of both the parent constructor and the new class'sconstructor:

Assigning the Visibility of Properties and

192021222324252627282930313233343536373839404142434445464748495051525354555657

echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; public function getProperty() return $this‐>prop1 . "<br />"; class MyOtherClass extends MyClass public function __construct() parent::__construct(); // Call the parent class's constructor echo "A new constructor in " . __CLASS__ . ".<br />"; public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; // Create a new object$newobj = new MyOtherClass; // Output the object as a stringecho $newobj‐>newMethod(); // Use a method from the parent classecho $newobj‐>getProperty(); ?>

12345

The class "MyClass" was initiated!A new constructor in MyOtherClass.From a new method in MyOtherClass.I'm a class property!The class "MyClass" was destroyed.

Page 19: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 19/44

Assigning the Visibility of Properties andMethods

For added control over objects, methods and properties are assigned visibility. Thiscontrols how and from where properties and methods can be accessed. There arethree visibility keywords: public , protected , and private . In addition to itsvisibility, a method or property can be declared as static , which allows them to beaccessed without an instantiation of the class.

"For added control over objects, methods andproperties are assigned visibility."

Note — Visibility is a new feature as of PHP 5. For information on OOP compatibilitywith PHP 4, see the PHP manual page.

Public Properties and MethodsAll the methods and properties you've used so far have been public. This means thatthey can be accessed anywhere, both within the class and externally.

Protected Properties and MethodsWhen a property or method is declared protected , it can only be accessed withinthe class itself or in descendant classes (classes that extend the class containingthe protected method).

Declare the getProperty() method as protected in MyClass and try to access itdirectly from outside the class:

0102030405060708091011

12

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />';

public function __destruct()

Page 20: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 20/44

Upon attempting to run this script, the following error shows up:

12131415161718192021222324252627282930313233343536373839404142434445464748495051525354

public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; protected function getProperty() return $this‐>prop1 . "<br />"; class MyOtherClass extends MyClass public function __construct() parent::__construct();echo "A new constructor in " . __CLASS__ . ".<br />"; public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; // Create a new object$newobj = new MyOtherClass; // Attempt to call a protected methodecho $newobj‐>getProperty(); ?>

1234

The class "MyClass" was initiated!A new constructor in MyOtherClass. Fatal error: Call to protected method MyClass::getProperty() from context

Page 21: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 21/44

Now, create a new method in MyOtherClass to call the getProperty() method:

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; protected function getProperty() return $this‐>prop1 . "<br />"; class MyOtherClass extends MyClass public function __construct() parent::__construct();echo "A new constructor in " . __CLASS__ . ".<br />"; public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; public function callProtected() return $this‐>getProperty();

Page 22: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 22/44

This generates the desired result:

Private Properties and MethodsA property or method declared private is accessible only from within the classthat defines it. This means that even if a new class extends the class that defines aprivate property, that property or method will not be available at all within the childclass.

To demonstrate this, declare getProperty() as private in MyClass , and attempt tocall callProtected() fromMyOtherClass :

50515253545556575859

// Create a new object$newobj = new MyOtherClass; // Call the protected method from within a public methodecho $newobj‐>callProtected(); ?>

1234

The class "MyClass" was initiated!A new constructor in MyOtherClass.I'm a class property!The class "MyClass" was destroyed.

01020304050607080910111213141516

17

<?php class MyClass public $prop1 = "I'm a class property!"; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />';

public function __toString()

Page 23: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 23/44

Reload your browser, and the following error appears:

17181920212223242526272829303132333435363738394041424344454647484950515253545556575859

public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; private function getProperty() return $this‐>prop1 . "<br />"; class MyOtherClass extends MyClass public function __construct() parent::__construct(); echo "A new constructor in " . __CLASS__ . ".<br />"; public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; public function callProtected() return $this‐>getProperty(); // Create a new object$newobj = new MyOtherClass; // Use a method from the parent classecho $newobj‐>callProtected(); ?>

1234

The class "MyClass" was initiated!A new constructor in MyOtherClass. Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass'

Page 24: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 24/44

Static Properties and MethodsA method or property declared static can be accessed without first instantiatingthe class; you simply supply the class name, scope resolution operator, and theproperty or method name.

"One of the major benefits to using static properties isthat they keep their stored values for the duration of thescript."

To demonstrate this, add a static property called $count and a static method calledplusOne() to MyClass . Then set up a do...while loop to output the incrementedvalue of $count as long as the value is less than 10:

010203040506070809101112131415161718192021222324252627282930313233

<?php class MyClass public $prop1 = "I'm a class property!"; public static $count = 0; public function __construct() echo 'The class "', __CLASS__, '" was initiated!<br />'; public function __destruct() echo 'The class "', __CLASS__, '" was destroyed.<br />'; public function __toString() echo "Using the toString method: "; return $this‐>getProperty(); public function setProperty($newval) $this‐>prop1 = $newval; private function getProperty()

return $this‐>prop1 . "<br />";

Page 25: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 25/44

Note — When accessing static properties, the dollar sign( $ ) comes after the scope resolution operator.

When you load this script in your browser, the following is output:

33343536373839404142434445464748495051525354555657585960616263646566

return $this‐>prop1 . "<br />"; public static function plusOne() return "The count is " . ++self::$count . ".<br />"; class MyOtherClass extends MyClass public function __construct() parent::__construct(); echo "A new constructor in " . __CLASS__ . ".<br />"; public function newMethod() echo "From a new method in " . __CLASS__ . ".<br />"; public function callProtected() return $this‐>getProperty(); do // Call plusOne without instantiating MyClass echo MyClass::plusOne(); while ( MyClass::$count < 10 ); ?>

01020304050607080910

The count is 1.The count is 2.The count is 3.The count is 4.The count is 5.The count is 6.The count is 7.The count is 8.

The count is 9.

Page 26: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 26/44

Commenting with DocBlocks

"The DocBlock commenting style is a widelyaccepted method of documenting classes."

While not an official part of OOP, the DocBlock commenting style is a widelyaccepted method of documenting classes. Aside from providing a standard fordevelopers to use when writing code, it has also been adopted by many of the mostpopular software development kits (SDKs), such as Eclipse and NetBeans, and willbe used to generate code hints.

A DocBlock is defined by using a block comment that starts with an additionalasterisk:

The real power of DocBlocks comes with the ability to use tags, which start with anat symbol ( @ ) immediately followed by the tag name and the value of the tag.DocBlock tags allow developers to define authors of a file, the license for aclass, the property or method information, and other useful information.

The most common tags used follow:

@author: The author of the current element (which might be a class, file,method, or any bit of code) are listed using this tag. Multiple author tags can beused in the same DocBlock if more than one author is credited. The format forthe author name is John Doe <[email protected]> .@copyright: This signifies the copyright year and name of the copyright holderfor the current element. The format is 2010 Copyright Holder .@license: This links to the license for the current element. The format for the

license information is

10 The count is 9.The count is 10.

123

/** * This is a very basic DocBlock */

Page 27: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 27/44

license information ishttp://www.example.com/path/to/license.txt License Name .@var: This holds the type and description of a variable or class property. Theformat is type element description .@param: This tag shows the type and description of a function or methodparameter. The format is type $element_name element description .@return: The type and description of the return value of a function or methodare provided in this tag. The format is type return element description .

A sample class commented with DocBlocks might look like this:

01020304050607080910111213141516171819202122232425262728293031323334353637

38

<?php /** * A simple class * * This is the long description for this class, * which can span as many lines as needed. It is * not required, whereas the short description is * necessary. * * It can also span multiple paragraphs if the * description merits that much verbiage. * * @author Jason Lengstorf <[email protected]> * @copyright 2010 Ennui Design * @license http://www.php.net/license/3_01.txt PHP License 3.01 */class SimpleClass /** * A public variable * * @var string stores data for the class */ public $foo; /** * Sets $foo to a new value upon class instantiation * * @param string $val a value required for the class * @return void */ public function __construct($val) $this‐>foo = $val;

/**

Page 28: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 28/44

Once you scan the preceding class, the benefits of DocBlock are apparent:everything is clearly defined so that the next developer can pick up the code andnever have to wonder what a snippet of code does or what it should contain.

Comparing ObjectOriented and ProceduralCode

There's not really a right and wrong way to write code. That being said, this sectionoutlines a strong argument for adopting an objectoriented approach insoftware development, especially in large applications.

Reason 1: Ease of Implementation

"While it may be daunting at first, OOP actuallyprovides an easier approach to dealing with data."

While it may be daunting at first, OOP actually provides an easier approach todealing with data. Because an object can store data internally, variables don't needto be passed from function to function to work properly.

Also, because multiple instances of the same class can exist simultaneously, dealing

3839404142434445464748495051525354

/** * Multiplies two integers * * Accepts a pair of integers and returns the * product of the two. * * @param int $bat a number to be multiplied * @param int $baz a number to be multiplied * @return int the product of the two parameters */ public function bar($bat, $baz) return $bat * $baz; ?>

Page 29: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 29/44

Also, because multiple instances of the same class can exist simultaneously, dealingwith large data sets is infinitely easier. For instance, imagine you have two people'sinformation being processed in a file. They need names, occupations, and ages.

The Procedural ApproachHere's the procedural approach to our example:

When executed, the code outputs the following:

010203040506070809101112131415161718192021222324252627282930313233343536373839404142

<?php function changeJob($person, $newjob) $person['job'] = $newjob; // Change the person's job return $person; function happyBirthday($person) ++$person['age']; // Add 1 to the person's age return $person; $person1 = array( 'name' => 'Tom', 'job' => 'Button‐Pusher', 'age' => 34); $person2 = array( 'name' => 'John', 'job' => 'Lever‐Puller', 'age' => 41); // Output the starting values for the peopleecho "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>"; // Tom got a promotion and had a birthday$person1 = changeJob($person1, 'Box‐Mover');$person1 = happyBirthday($person1); // John just had a birthday$person2 = happyBirthday($person2); // Output the new values for the peopleecho "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>"; ?>

Page 30: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 30/44

When executed, the code outputs the following:

While this code isn't necessarily bad, there's a lot to keep in mind while coding. Thearray of the affected person's attributes must be passed and returned fromeach function call, which leaves margin for error.

To clean up this example, it would be desirable to leave as few things up to thedeveloper as possible. Only absolutely essential information for the currentoperation should need to be passed to the functions.

This is where OOP steps in and helps you clean things up.

The OOP ApproachHere's the OOP approach to our example:

010203040506070809101112131415161718192021222324

Person 1: Array( [name] => Tom [job] => Button‐Pusher [age] => 34)Person 2: Array( [name] => John [job] => Lever‐Puller [age] => 41)Person 1: Array( [name] => Tom [job] => Box‐Mover [age] => 35)Person 2: Array( [name] => John [job] => Lever‐Puller [age] => 42)

01020304

05

<?php class Person

private $_name;

Page 31: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 31/44

This outputs the following in the browser:

050607080910111213141516171819202122232425262728293031323334353637383940414243444546

private $_name; private $_job; private $_age; public function __construct($name, $job, $age) $this‐>_name = $name; $this‐>_job = $job; $this‐>_age = $age; public function changeJob($newjob) $this‐>_job = $newjob; public function happyBirthday() ++$this‐>_age; // Create two new people$person1 = new Person("Tom", "Button‐Pusher", 34);$person2 = new Person("John", "Lever Puller", 41); // Output their starting pointecho "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>"; // Give Tom a promotion and a birthday$person1‐>changeJob("Box‐Mover");$person1‐>happyBirthday(); // John just gets a year older$person2‐>happyBirthday(); // Output the ending valuesecho "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>"; ?>

010203040506

07

Person 1: Person Object( [_name:private] => Tom [_job:private] => Button‐Pusher [_age:private] => 34)

Page 32: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 32/44

There's a little bit more setup involved to make the approach object oriented, butafter the class is defined, creating and modifying people is a breeze; a person'sinformation does not need to be passed or returned from methods, and onlyabsolutely essential information is passed to each method.

"OOP will significantly reduce your workload ifimplemented properly."

On the small scale, this difference may not seem like much, but as your applicationsgrow in size, OOP will significantly reduce your workload if implemented properly.

Tip — Not everything needs to be object oriented. A quick function that handlessomething small in one place inside the application does not necessarily need to bewrapped in a class. Use your best judgment when deciding between objectorientedand procedural approaches.

Reason 2: Better Organization

Another benefit of OOP is how well it lends itself to being easily packaged and

cataloged. Each class can generally be kept in its own separate file, and if a uniform

070809101112131415161718192021222324252627

Person 2: Person Object( [_name:private] => John [_job:private] => Lever Puller [_age:private] => 41) Person 1: Person Object( [_name:private] => Tom [_job:private] => Box‐Mover [_age:private] => 35) Person 2: Person Object( [_name:private] => John [_job:private] => Lever Puller [_age:private] => 42)

Page 33: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 33/44

cataloged. Each class can generally be kept in its own separate file, and if a uniformnaming convention is used, accessing the classes is extremely simple.

Assume you've got an application with 150 classes that are called dynamicallythrough a controller file at the root of your application filesystem. All 150 classesfollow the naming convention class.classname.inc.php and reside in the incfolder of your application.

The controller can implement PHP's __autoload() function to dynamically pull inonly the classes it needs as they are called, rather than including all 150 in thecontroller file just in case or coming up with some clever way of including the files inyour own code:

Having each class in a separate file also makes code more portable and easier toreuse in new applications without a bunch of copying and pasting.

Reason 3: Easier Maintenance

Due to the more compact nature of OOP when done correctly, changes in the codeare usually much easier to spot and make than in a long spaghetti codeprocedural implementation.

If a particular array of information gains a new attribute, a procedural piece ofsoftware may require (in a worstcase scenario) that the new attribute be added toeach function that uses the array.

An OOP application could potentially be updated as easily adding the new propertyand then adding the methods that deal with said property.

A lot of the benefits covered in this section are the product of OOP in combination

123456

<?php function __autoload($class_name) include_once 'inc/class.' . $class_name . '.inc.php'; ?>

Page 34: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 34/44

A lot of the benefits covered in this section are the product of OOP in combinationwith DRY programming practices. It is definitely possible to create easytomaintain procedural code that doesn't cause nightmares, and it is equally possible tocreate awful objectoriented code. [Pro PHP and jQuery] will attempt to demonstratea combination of good coding habits in conjunction with OOP to generate clean codethat's easy to read and maintain.

Summary

At this point, you should feel comfortable with the objectoriented programming style.Learning OOP is a great way to take your programming to that next level. Whenimplemented properly, OOP will help you produce easytoread, easytomaintain,portable code that will save you (and the developers who work with you) hours ofextra work. Are you stuck on something that wasn't covered in this article? Are youalready using OOP and have some tips for beginners? Share them in the comments!

Author's Note — This tutorial was an excerpt from Pro PHP and jQuery (Apress,2010).

Difficulty:Intermediate

Length:Long

Categories:

Page 35: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 35/44

Suggested Tuts+ Course

Related Tutorials

Categories:

BackEnd PHP Programming Fundamentals OOP

ObjectOriented Programming

Translations Available:PусскийPortuguês

Tuts+ tutorials are translated by our community members. If you'd like to translate this post into another language, letus know!

Translations powered by

About Jason Lengstorf

Jason Lengstorf is a 25yearold turbogeek hailing from Portland, Oregon, who designs and developswebsites for Copter Labs. He's the author of PHP for Absolute Beginners [2009 Apress] and Pro PHP andjQuery [2010 Apress], as well as articles for various online publications.

The Swift Programming Language $15

Create a License Controlled Plugin and Theme Update System, Part 3: Doing the UpdateCode

Programming With Yii2: Exploring MVC, Forms and Layouts

Page 36: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 36/44

Jobs

Envato Market Item

625 Comments Nettuts+ Login

Share⤤ Sort by Best

Join the discussion…

• Reply •

lollypopgr • 2 years agoProbably the best OOP PHP tutorial I have read. Congratulations.

306

ISH • 2 years ago> lollypopgr

I second this comment!

Recommend 52

Share ›

Code

Design Patterns: The Decorator PatternCode

Business Writerat Tuts+ in New York, NY, USA

Web Designer / Graphic Designerin Valletta, Malta

Page 37: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 37/44

• Reply •

I second this comment! 38

• Reply •

Jamie • 2 years ago> ISH

I third it! Good effort and shared! 32

• Reply •

Altin • 2 years ago> Jamie

I absolutely TENth it :D 22

• Reply •

tony2002 • 2 years ago> Altin

Best oop tutorial ever. 20

• Reply •

mm2012 • 2 years ago> Jamie

I fourth it :) I'll be using OOP PHP soon because of this tutorial. 15

• Reply •

Tofunmi • 2 years ago> mm2012

I fifth it.thumbs up Jason 10

• Reply •

MrBoubou • 2 years ago> mm2012

I fifth it ! (if that is how 'fifth' should be written, idk im french, but you getthe point) :D

7

• Reply •

imnaved • 2 years ago> MrBoubou

This is the sixth one... haha :P 10

• Reply •

Gyanendra • 2 years ago> imnaved

I 7th,,, :) 9

• Reply •

maika • 2 years ago> Gyanendra

i 8th 5

• Reply •

IHumblyThankYou • 2 years ago> maika

9th(from Namibia) 5

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Page 38: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 38/44

• Reply •

Carnal • 2 years ago> IHumblyThankYou

10th from the Philippines! 6

• Reply •

Kashif • 2 years ago> Carnal

I got cleared idea about OOP after reading this tutorial, Now I know whatis class, object, initializing object, Constructor, Destructor, Method,properties, inheritance, Access Specifiers, Thx

6

• Reply •

Saif Rahman • a year ago> Kashif

my poor brain is now at ease after all the other garbage vids andtutorials which i tried understanding the basics of oop in php.

Thank you to the author for defragmenting my brain 13

• Reply •

wafiq • a year ago> Saif Rahman

I feel the same way i wish i'd of read this 2 years ago i remember havingan over the phone interview for a PHP role and giving a somewhatconfusing unclear answer when asked to explain OOP after having readthrough the same type of garbage tutorials and books. Cant believe imissed this one, Ive been learning Ruby since then which has helped.

A late thanx for the article. 3

• Reply •

666 • a year ago> mm2012

6666666666 2

• Reply •

Mr. Lima • 2 years ago> lollypopgr

I 10th (from Brazil) 8

• Reply •

Jaina • 2 years ago> lollypopgr

I 11th it! I've read books and articles and watched videos. Nothing is better,CONGRATULATIONS, great great great! :D

4

• Reply •

RalphAlex • a year ago> lollypopgr

Best one 3

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Page 39: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 39/44

• Reply •

maximus • a year ago> lollypopgr

GREAT tutorial! Loved it. So simple and easy to understand 2

• Reply •

Kwasi • 2 years ago> lollypopgr

I tenth it from Ghana 2

• Reply •

richie • 2 years ago> Kwasi

mr. kwasi. youve seen how youve benefited from this tutorial. your Ghanaianfriend will ask you for the same kind of help and you wont help. thats how a lotof Ghanaian are. from a Ghanaian.

4

• Reply •

Tabe • 7 months ago> richie

Don't fight ma brotha's. To help the need, there must be time. I'm sureMr. Kwasi is a very busy man doing his own things which he find moreimportant than helping you. Sometimes, we need to help ourself on thisharsh world brotha. Keep strong, keep going, andb e succesful. Froma Cameroonian.

• Reply •

Mike • 6 months ago> lollypopgr

Thanks Jason. Best OOP PHP class.

• Reply •

Berenice • 7 months ago> lollypopgr

I agree!!!! lollypopgr

• Reply •

arash • 10 months ago> lollypopgr

affirmative

• Reply •

Nathan Robb • a year ago> lollypopgr

Amazing OOP tutorial. I've been programming in C# for some time now, and readingthis about OOP PHP is exactly what I was looking for. Thumbs up!

• Reply •

Nihal Sahu • a year ago> lollypopgr

I eleventh it . If such a phrase exists

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Page 40: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 40/44

• Reply •

Laura D. • 2 years agoI've been trying to wrap my head around OOP for years, and this one tutorial has helped meunderstand more about it than every single resource I've found thusfar. I still have a bit to gobefore I am doing complex things, but now that I have a basic understanding, I can definitelysee it being used to my benefit. Thank you for this article, Jason.

28

• Reply •

Wayne L. • a year ago> Laura D.

Even though this comment is a year old I am sooooooo glad that I am not alone. Thiscomment sums up exactly what I was thinking. :D +25

6

• Reply •

Paulo Madroñero • 8 months ago> Wayne L.

Maybe you, guys already know well the OOP, why i didn't read this article a fewyears ago?!

• Reply •

win • 2 years agosuddenly i feel i learn so much thanks!

21

• Reply •

Sara • 3 years agoI've fallen in love with OOP programming since I first started my first java course in college, Ilove the logic and ease of OOP. Thank you for this article, I see that there's not muchdifference between the syntax of OOP in the different OO languages and this is a good thing.Thanks again :)

16

• Reply •

Vishal Jaiswal • 2 years ago> Sara

hi sara u r right 5

• Reply •

Nebojsa • a year ago> Sara

Sara, OOP is something that's totally separate from PHP or Java. It is onlyimplemented in PHP and Java. It is way of thinking and organizing stuff.

2

Prabhu Nandan Kumar • 2 years agoReally very simple and understandable way is used to write this OOP PHP tutorial . I wannacongratulate to writer for this tutorial.

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Page 41: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 41/44

• Reply • 17

• Reply •

Bijai Kumar Dwivedi • a year agofrom last 4years i was always thinking that i will never understand the OOPs and Classes inPHP. But after reading the above tutorial i found my self wrong and a lot of thankful to theauthor.Thanks.It's really a good tutorial.

9

• Reply •

Benny • 4 months ago> Bijai Kumar Dwivedi

yes very clear!

melo • 2 years agoThank you so much for this tutorial! It really helped gain a better understanding of OOP, earlierit was something that I saw no particular use for and really dreaded using it. As I am a beginnerI have a question unrelated to OOP (I assume, at least): echo 'The class "', __CLASS__, '" was initiated!';"A new constructor in " . __CLASS__ . ".";

Why were there literals and commas used in the first example and double quotes and dots in

Share ›

Share ›

Share ›

Page 42: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 42/44

• Reply •

the other? What's the key difference? Is it just for adding regular double quotes to the first onewith literals?

8

• Reply •

Chase • 2 years ago> melo

bump, I'm wondering this too. 3

• Reply •

Travis • 2 years ago> Chase

In PHP a period is used for concatenation. Where he uses a comma I think is atypo as it sits literally next to the period and just wasn't caught before beingpublished. Stick with periods.

3

• Reply •

Matt • 2 years ago> Travis

echo can be used with commas and periods for concatenation.Good article here: http://www.electrictoolbox.com...

3

• Reply •

Deepak • a year ago> Matt

WOW, Never ever tried it. Just tried and it works, Thank you!

• Reply •

A.S. • 2 years ago> melo

I don't get this either! The second line (where dot is used for concatenation) makessense to me but not the first.

1

• Reply •

ChrisHE • a year ago> A.S.

Answer to the above see the php manual for echo. Basically it can output oneOR more strings. Using the period concatenates strings into a single string,whereas commas use the fact that echo will accept MORE than one string, andoutput them all.So either way is acceptable. Note also that using single quotes will output the variable name, whereas insidedouble quotes echo will output the variable VALUE.HTH

1

OOP • 5 years agoI've been programming in c++ and java for a while and I've learned OOP at school since dayone. I still can't figure out why I would use it on a website(Not a web app). I don't see myselfmaking a class for different elements of a website to segment it into something more logicalcodewise. It's strange because if it comes to making desktop applications I have no issue at

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Page 43: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 43/44

19,319 Tutorials 502 Video Courses

• Reply •

codewise. It's strange because if it comes to making desktop applications I have no issue atall at making it Object oriented.

I remember back in the time when my PHP teacher showed us a calendar made in objectoriented PHP and that's pretty much the only thing I can think of for it's use; plugins, and then Iwould resort to JS for that kind of stuff...

I'd need to see the class structure of a regular website to see how people manage it and howthey split different elements into classes cause the rest is exactly like in any other language.

6

RAMON a year ago> OOP

Share ›

Teaching skills to millions worldwide.

Follow Us

Help and Support

FAQTerms of UseContact SupportAbout Tuts+AdvertiseTeach at Tuts+

Page 44: Object-Oriented PHP for Beginners - Tuts+ Code Tutorial

3/26/2015 ObjectOriented PHP for Beginners Tuts+ Code Tutorial

http://code.tutsplus.com/tutorials/objectorientedphpforbeginnersnet12762 44/44

Custom digital services like logo design, WordPress installation, video productionand more.

Check out Envato Studio

Build anything from social networks to file upload systems. Build faster with precoded PHP scripts.

Browse PHP on CodeCanyon

Teach at Tuts+

Email Newsletters

Get Tuts+ updates, news, surveys &offers.

Email Address

Subscribe

Privacy Policy

© 2015 Envato Pty Ltd. Trademarks and brands are the property of their respective owners.