Solved

PHP 5 OOP Capabilities

Posted on 2004-04-13
19
627 Views
Last Modified: 2007-12-19
I've been doing some reading up on websites (Zend, and other independent sites), but I still do not understand why PHP 5's OOP is way better than 4's. Could somebody explain to me in layman's terms and show me some examples where PHP 5 OOP's come in handy over PHP 4's?
0
Comment
Question by:drakkarnoir
  • 10
  • 8
19 Comments
 
LVL 7

Expert Comment

by:madwax
Comment Utility
PHP5 has single-inheritance, access-restricted and overloadable object model.

Single inheritance is one parent per child.
Access-restriction - PHP supports now restriction to properties and methods. In other words you will be able to use all the functions in other languages, static, public private etc.
Overloadable is that a child class allows to overload the members of it's parent class. You may be able to overload constructors since they are going to be called __construct(), destructors etc.

The biggest change is that the new engine treats the objects differently from other kind of values aviablabel in PHP and inplements implicit, pass-by-reference behaviour. That is, PHP does not require you to explicitly pass or return objects by reference. The handle-based object model is the most important new featrue of PHP5.

You may furthermore use patterns thanks to the overloadability, e.g. singletonpattern, observerpattern, factorypattern etc.

Hope this gave you some more information. To conclude you may say that the new PHP5 object model transforms PHP into a real OO language from being something in the middle between a procedural and a OO language. And the biggest difference lies in the more advanced areas of OO.

//jan
0
 

Author Comment

by:drakkarnoir
Comment Utility
Still don't understand how treating objects differently would effect or enhance my coding ability.
0
 
LVL 7

Accepted Solution

by:
madwax earned 500 total points
Comment Utility
For instance before PHP5 it was hard to implement a singleton pattern ( that is a pattern that makes sure that you only have one instance of a class att any single time). A singleton pattern applied on a configuration (you only want to have one configuration class at the time, or sure I want to :) ) class may look as follows: (example from Leon Atkinsons Core PHP Programming):

<?php
      /*
      ** Configuration file singleton
      */
      class Configuration
      {
            static private $instance = NULL;
            private $ini_settings;
            private $updated = FALSE;
            const INI_FILENAME = "/tmp/corephp.ini";

            private function __construct()
            {
                  if(file_exists(self::INI_FILENAME))
                  {
                        $this->ini_settings =
                              parse_ini_file(self::INI_FILENAME);
                  }
            }

            private function __destruct()
            {
                  //if configuration hasn't changed, no need
                  //to update it on disk
                  if(!$this->updated)
                  {
                        return;
                  }
      
                  //overwrite INI file with the
                  //version in memory
                  $fp = fopen(self::INI_FILENAME, "w");
                  if(!$fp)
                  {
                        return;
                  }

                  foreach ($this->ini_settings as $key => $value)
                  {
                        fputs($fp, "$key = \"$value\"\n");
                  }

                  fclose($fp);
            }

            public function getInstance()
            {
                  if(self::$instance == NULL)
                  {
                        self::$instance = new Configuration();
                  }
      
                  return self::$instance;
            }

            public function get($name)
            {
                  if(isset($this->ini_settings[$name]))
                  {
                        return $this->ini_settings[$name];
                  }
                  else
                  {
                        return(NULL);
                  }
            }

            public function set($name, $value)
            {
                  //update only if different from what
                  //we already have
                  if(!isset($this->ini_settings[$name]) OR
                        ($this->ini_settings[$name] != $value))
                  {
                        $this->ini_settings[$name] = $value;
                        $this->updated = TRUE;
                  }
            }
      }

      //Test the class
      $config = Configuration::getInstance();
      $config->set("username", "leon");
      $config->set("password", "secret");
      print($config->get("username"));
?>
0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
in the class above I would like to point out for example the construction of the methods and declaration oc properties:

static private $instance = NULL;
private $ini_settings;
private $updated = FALSE;

The private and static keywords are new and makes sure that the (private)properties are NOT accessible from outside, as are not the construct och destruct methods. It's small changes when we look at it, but from a design point of view or a memory managing point of view the differences are enormous.

Sorry that I am not able to explain it better than this... =/

//jan
0
 

Author Comment

by:drakkarnoir
Comment Utility
The only thing I see in that example that I haven't seen in PHP 4, is the self:: (isn't that equilvant to $this-> ?) and private function __construct()/destruct(), what is the point of that?
0
 

Author Comment

by:drakkarnoir
Comment Utility
static private $instance = NULL;
private $ini_settings;
private $updated = FALSE;

These are being defined as how I learned them in C++, and I understand the scope deal, but how would this help in practical ways of the way we code PHP classes traditionally...
0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
Well, as I see it will not affect the way of coding more than it gives us more possibilities than before (with the methods above mentioned).

For example, if we return to the Singleton class Configuration. The private constrcutor prevetns users from instantiationg the class directly. They must use the getInstance method. Trying to instantiate the class using $obj = new Configuration will result in a fatal error since the global scope may not call the private constructor.

0
 

Author Comment

by:drakkarnoir
Comment Utility
Since the global scope cannot call:

private function __construct()
          {
               if(file_exists(self::INI_FILENAME))
               {
                    $this->ini_settings =
                         parse_ini_file(self::INI_FILENAME);
               }
          }

Specifically?
0
 

Author Comment

by:drakkarnoir
Comment Utility
And is like private function __construct() the entry point of the class?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 7

Expert Comment

by:madwax
Comment Utility
This possibility to hide the constructor is unheard of prior to PHP5.

As I see it the only way it is going to effect is if we choose it to do. We will still be able to use our normal constructors and code the "old" way since PHP5 is backward compatible. Mostly how it is going to affect my coding, is by this example as I showed you where I will be able to code my applications in a real OO way. Then I agree with you that it isn't that interesting how the new garbage collector in the engine works, or how it treats it's object... :D
0
 

Author Comment

by:drakkarnoir
Comment Utility
Yeah, I just saw a lot of hype around it...and I couldn't figure out what all the fuss was about. I mean, I think register_globals going to a default OFF setting should have called for more discussion and debating, since it disabled a lot of the $_ENV variables with it (SCRIPT_URI, etc).

Anyways, here's a class from a while back:

class Auth {

  1: function Auth($storageDriver = "DB", $options = "", $loginFunction = "", $showLogin = true)
  2:     {
  3:         if ($loginFunction != "" && function_exists($loginFunction)) {
  4:             $this->loginFunction = $loginFunction;
  5:         }
  6:
  7:         if (is_bool($showLogin)) {
  8:             $this->showLogin = $showLogin;
  9:         }
 10:
 11:         $this->storage = $this->_factory($storageDriver, $options);
 12:     }

}

How would I recode that class to take advantage of PHP 5 OOP's abilities? And what would I gain doing it? Also, what differences would:

function _factor {
}
and
function __factor {
}

Have?
0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
>>And is like private function __construct() the entry point of the class?

In this case since it's private - no, it is the getInstance()-method.
In normal cases yes, the __constructor() will be the entrypoint to the class.

By using static we can acces it even before it is instantiated = big difference... =o)

0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
You wont't be able to write:

function __factor {
}

since it as I understood it the __-prefix is only applicible to constructors and destructors.

With PHP5 you will be able to do the following:

namespace ivtaco:utility{
      abstract class Shape
      {
            abstract function getArea();
      }

      //abstract child class
      abstract class Polygon extends Shape
      {
            abstract function getNumberOfSides();
      }

      //concrete class
      class Triangle extends Polygon
      {
            public $base;
            public $height;

            public function getArea()
            {
                  return(($this->base * $this->height)/2);
            }

            public function getNumberOfSides()
            {
                  return(3);
            }
      }

      //concrete class
      class Rectangle extends Polygon
      {
            public $width;
            public $height;

            public function getArea()
            {
                  return($this->width * $this->height);
            }

            public function getNumberOfSides()
            {
                  return(4);
            }
      }

      //concrete class
      class Circle extends Shape
      {
            public $radius;

            public function getArea()
            {
                  return(pi() * $this->radius * $this->radius);
            }
      }

      //concrete root class
      class Color
      {
            public $name;
      }
}










$myCollection = array();

      //make a rectangle
      $r = new Rectangle;
      $r->width = 5;
      $r->height = 7;
      $myCollection[] = $r;
      unset($r);

      //make a triangle
      $t = new Triangle;
      $t->base = 4;
      $t->height = 5;
      $myCollection[] = $t;
      unset($t);

      //make a circle
      $c = new Circle;
      $c->radius = 3;
      $myCollection[] = $c;
      unset($c);

      //make a color
      $c = new Color;
      $c->name = "blue";
      $myCollection[] = $c;
      unset($c);
      foreach($myCollection as $s)
      {
            if($s instanceof Shape)
            {
                  print("Area: " . $s->getArea() . "<br>\n");
            }

            if($s instanceof Polygon)
            {
                  print("Sides: " . $s->getNumberOfSides() . "<br>\n");
            }

            if($s instanceof Color)
            {
                  print("Color: $s->name<br>\n");
            }
            print("<br>\n");
      }
0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
To explain the above:

You can create hierchical abstract and concrete classes, write child class that allows to overload the members of it's parent class etc.

Ah, about your question, I misunderstood it but gotta run for now. But sincerely I don't really with a quick glance on it see how we could rewrite your function to take better advantage of php5... =/ sorry...
0
 
LVL 9

Expert Comment

by:techtonik
Comment Utility
Good Information, madwax! I've read this thread in one gulp. =)
0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
Thanks techtonik! Always great to get some appretiation :)

Back to the subject...

drakkarnoir, I don't think it would give you any advantages rewriting your class. As I wrote earlier, the largest differences lies hidden within the system and will hardly be noticable for the normal coder. As I see it will probably be mostly the same thing with PHP5, except for a number of new and rewritten libraries (I know gd will be native, as well tidy and a new XML parser that keeps up to the DOM specifications), some new advanced class-functinality (as mentioned above with new scope methods) and PHP takes a leap forward into being an application language and not just a scripting language anymore. I have namely seen some betas of standalone applications. To conclude, if you don't want it to, it won't affect your coding at all - old programs are said to work, which means all the oldy styles will function.

But I personally think when we are looking into the future, both for PHP and our own applications, it is a good idea to try to adapt the new way with declaring and implementing classes. I base this on the assumptions that it will slowly go into the same directions as the disabling of REGISTER_GLOBAL - you can have it turned ON, but it is recommendable for several reasons to have it set of. The same thing I think will happen with class-declarations, one SHOULD but class-variables private, and functions public etc.

Phuu... this is the most I have written on EE in one single question sofar... =o)


I really hope you have a better view of what _possibilities_ PHP5 will bring us...
//jan
0
 
LVL 7

Expert Comment

by:madwax
Comment Utility
drakkarnoir >> I hope that this answered your question? I namely liked this discussion and I would like to hear your additional comments on this matter... =)
0
 

Author Comment

by:drakkarnoir
Comment Utility
Yeah, I think I got the hang of it now...thanks!
0
 

Author Comment

by:drakkarnoir
Comment Utility
All the fuss was just making me wonder hehe.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now