Solved

PHP 5 OOP Capabilities

Posted on 2004-04-13
19
629 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
ID: 10815518
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
ID: 10815546
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
ID: 10815548
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
ID: 10815577
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
ID: 10815585
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
ID: 10815594
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
ID: 10815680
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
ID: 10815696
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
ID: 10815699
And is like private function __construct() the entry point of the class?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 7

Expert Comment

by:madwax
ID: 10815720
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
ID: 10815806
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
ID: 10815807
>>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
ID: 10815876
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
ID: 10815939
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
ID: 10817784
Good Information, madwax! I've read this thread in one gulp. =)
0
 
LVL 7

Expert Comment

by:madwax
ID: 10821159
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
ID: 10831045
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
ID: 10833701
Yeah, I think I got the hang of it now...thanks!
0
 

Author Comment

by:drakkarnoir
ID: 10833705
All the fuss was just making me wonder hehe.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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 …

863 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

23 Experts available now in Live!

Get 1:1 Help Now