jump to navigation

The basics of OOP with PHP October 10, 2010

Posted by Tournas Dimitrios in PHP.
trackback

Object oriented programming (OOP) is a must know issue , even for non programmers like me . The same concepts apply (with smooth deviations) on all programming languages , no matter if it has to do with Java , C++ , Actionscript 3  etc… So please – please – please invest your time to get at least a basic understanding .You will get your money back , promise you 🙂 . Lets get started ……

The object oriented programming concept is great for not only organizing code, but also easing readability. Creating a class in PHP is easy and we will go through the basics. For starters, creating a PHP class is as easy as:

class myFirstClass {
   // CLASS CONTENT GOES HERE
}

The next step is to add variables and functions to the class. One of the first functions every class has is a constructor. A constructor is a function that is run when the class object is created. To create a constructor function for your class, a default constructor function name by “__construct()” is used. See the example below

class myFirstClass {
   public function __construct() {
      // CONSTRUCTOR CONTENT HERE
   }
}

Next, you can add variables to your class. Variables can be defined as public or private. Private variables can be accessed only from functions belonging to the class. Public variables on the other hand can be accessed by functions belonging to the class along with functions outside the class. Once we have defined our variables, we can initialize them in our constructor. Below is an expanded example of a public and private variable.

.
class myFirstClass {
   private $myPrivateVariable;
   public $myPublicVariable;

   public function __construct() {
      $this->myPrivateVariable = "Private Message";
      $this->myPublicVariable = "Public Message";
   }
}

.

Lastly, we can add functions to our class. Because the $myPrivateVariable is private, we cannot assign it without a custom function. Therefore, in our next example, we will create a function that assigns a string value to the $myPrivateVariable. This function should be public since we want to be able to access it from outside of the class.

class myFirstClass {
   private $myPrivateVariable;
   public $myPublicVariable;

   public function __construct() {
      $this->myPrivateVariable = "Private Message";
      $this->myPublicVariable = "Public Message";
   }

   public function assignMyPrivateVariable($message) {
      $this->myPrivateVariable = $message;
   }
}

Now, we have completed a very basic PHP class. Follow the same steps to create more variables and more functions to make the class more powerful and useful.

Accessing PHP Class Variables and Functions :

So you have successfully created a PHP class and want access to the classes variables and functions. As a reminder to programming beginners, you can only access public variables and public functions. That is a function or variable that was declared with the public keyword or no keyword (as PHP functions and variables are by default public). Below is a quick refresher example where functionNumberOne and functionNumberTwo are public and functionNumberThree is private.

class Common {
   public $secondVariable = "2";
   private $thirdVariable = "3";

   function functionNumberOne() {
      echo "This is my first function";
   }

   public function functionNumberTwo() {
      echo "This is my second function";
   }

   private function functionNumberThree() {
      echo "This is my third function";
   }
}

If the class is declared in another a separate file, remember to first include the file before your first attempt to access the class. Generally, the best place to include files is at the very top of the file.

Assuming our Common class function above, our first step to accessing our PHP variables and functions is to create an object. In programming terms, this is known as initializing an object instance. To create the class instance:

$myInstance = new Common();

How was the previous code snippet generated? You can choose any name to replace the $myInstance variable (so long as it is not a keyword). Next, new is a PHP keyword that in this situation signifies the creation of a new object. Finally, Common() is constructed by using the class name (in this case Common) followed by an open parenthesis and close parenthesis ‘()‘. If you have a specified a constructor, make sure you include the correct number of parameters.

Finally, to access the public variables we use the $myInstance object followed by ‘->’ and the public variable or function name. When accessing the variable name, you do not need to start with $. Again, we have a code example below.

.
echo $myInstance->secondVariable;
$myInstance->functionNumberOne();
$myInstance->functionNumberTwo();

.

And there we have it. You now have access to public PHP functions and PHP variables. Note that the use of classes is a new feature to PHP 5.

The Scope Resolution Operator :

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon :: allows us access to methods of a class. It is used in object-oriented programming when you want to be specific about what kind of function you are calling. The most common use for scope resolution is with the pseudo-class parent.
Two keywords, self and parent are used to access members or methods inside a class.

.
//Outside the Class
< ? p h p

class TalkPHPMail {
   const subject = 'Hello TalkPHP!';
}

echo TalkPHPMail::subject;

//////////////////////////////////
//Inside the Class
< ? p h p

class TalkPHPMail {
   const subject = 'Hello TalkPHP!';
   public function send() {
       echo self::subject;
   }
}

Final :
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

< ? p h p

final class TalkPHPMail {
   public function send() {
       echo "Sending....\n";
   }
}

class Subject extends TalkPHPMail {
 // This will result in a fatal error
}

Constructor/Destructor :

Classes come with two special methods called a constructor and a destructor. A constructor method will be called when a new instance of the class is created, and is commonly used to set the initial status of the class. Typical uses of the constructor include setting up a database connection or setting some default properties. The example below demonstrates the use of a constructor:

< ? p h p
Class MyCar {
  public $name;
  function __construct($name) {
  $this->name = $name;
        }

  function drive() {
  echo 'Vrooooom... ' . $this->name;
        }
      }

$porsche = new MyCar('Porsche');
$porsche->drive();

In the example above we used the constructor to set the $name property of our class. As you can see we passed an argument when creating a new instance of the class.For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.More examples .

The destructor is used to execute code when an object gets removed, by unsetting the object with the unset() function, or when the script ends. Usually the destructor is used to perform clean up tasks, such as closing database connections, saving data to the hard disk, etc. The example below demonstrates the destructor:

< ? p h p
Class MyCar {
  public $name;
 function __construct($name) {
 $this->name = $name;
        }
  function __destruct() {
  echo '*crash* this car has been destroyed';
        }

  function drive() {
  echo 'Vrooooom... ' . $this->name;
        }
}

// Instance 1
$porsche = new MyCar('Porsche');
$porsche->drive();

echo '';

unset($porsche);

Type Hinting :

Type hinting is a feature introduced with the PHP 5 release. Type hinting ensures that the object being
passed to the method is indeed a member of the expected class. For example, it makes sense that only
objects of class Employee should be passed to the takeLunchbreak() method. Therefore, you can preface
the method definition’s sole input parameter $employee with Employee, enforcing this rule. An example
follows:

private function takeLunchbreak(Employee $employee)
{

}

Keep in mind that type hinting only works for objects and arrays. You can’t offer hints for types such as integers, floats, or strings.

I hope you enjoyed the journey of OOP , keep focused  and I ‘ll post related articles in future post .

Advertisements

Comments»

1. PHP Static Method the basics « Tournas Dimitrios - October 10, 2010

[…] Method the basics October 10, 2010 Posted by tournasdimitrios1 in Uncategorized. trackback My previous article introduced the concept of OOP with PHP .Lets get dive a little deeper , and focusing on […]

2. Using the keyword “$this” in PHP « Tournas Dimitrios - October 11, 2010

[…] by tournasdimitrios1 in Uncategorized. trackback Welcome to another part of the serie ” The basics of OOP with PHP ” follow up […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s