Jump to content

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');

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.