Jump to content

Why use an uninstantiated class?


lanmonkey

Recommended Posts

I understand how it is possible to work with a class in its non-object form using the scope resolution operator ect….

 

But my question is: Why would you want to?

 

thanks

 

Sometimes you don't want an object, but rather one of its methods.  Factory classes are a common example of this:

 

class PersonFactory
{
   public static function getPerson($id)
   {
      $query = "SELECT * FROM people WHERE id = '$id'";
      $result = mysql_query($query);
      $row = mysql_fetch_assoc($result);

      $person = new Person($row['name'], $row['age']);

      return $person;
   }
}

class Person
{
   private $name;
   private $age;

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

$myPerson = PersonFactory::getPerson(22);

 

In this case, you don't need (or even want) to have a hold of a PersonFactory object.  You just need a specific Person object.

I've found doing so with a registry object can be handy.  It makes my registry available from anywhere a global would be, and I never have more than 1 registry object, never have to pass it to other classes, etc.

 

Example.

<?php
$errors=new Error();
Registry::set('error', $errors);

//To use the error object
Registry::$vars['error']->add_error('registration', 'You must type a username');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.