Understanding Static Properties with PHP 5

The powerful object model offered by PHP 5 presents some useful features that are quite frequently underestimated by the average PHP developer. This is precisely the case with using static methods and properties in conjunction with the object-oriented paradigm, thus if you’re interested in learning how to put static data to work for you, then this series of articles might be what you’re looking for.

Introduction

Welcome to the second part of the series that began with "Handling Static Data with PHP 5". As you might guess, this series shows you how to take advantage of defining static properties and methods with PHP 5 classes, and it complements the corresponding theoretical concepts with several illustrative hands-on examples.

If you already went through the first article of the series, then it’s quite possible that working with static data in PHP 5 is now a familiar concept to you. In that tutorial, I demonstrated, by way of a few simple (yet functional) examples, how to use a static method to implement the factory pattern. In truth, the definition and further utilization of a static method within a factory class can be considered almost a rule of thumb when it comes to factoring different objects during a the execution of a given PHP application.

The subject, however, goes by far beyond defining a static method as part of a simple factory class. And I’m saying this because admittedly, working with static data in PHP 5 might be incredibly useful in certain cases, a fact that you might not have been aware of until now. Thus, provided that you already have an average background in using static methods with PHP 5, over the course of this second article of the series I’ll dive a bit deeper into this interesting  topic and show you how to take advantage of static properties defined inside a given PHP class, in this manner completing, at least basically, the implementation of static data with PHP 5.

Even though the term "static" sounds like it refers to a thing that does nothing, in the new few lines you’ll be hopefully surprised at the great range of PHP applications that can incorporate the remarkable benefits of using static properties in their classes.

Having introduced the subject of this second installment of the series, it’s time to step forward and continue learning with more examples of how to use static properties with PHP 5. It’s going to be an educational journey, trust me!

{mospagebreak title=Reintroducing a previous hands-on example}

For the sake of completeness, before I start explaining how to define and use static properties in a helpful fashion with PHP 5, first I’d like to remind you quickly of the implementation of a static method as part of the so-called factory pattern that was discussed in the preceding tutorial of the series. In doing so, hopefully you’ll be better prepared to take the next step in this learning process and grasp more quickly the usage of static properties in PHP 5 classes.

So, having explained that, now have a look at the following sample PHP classes. These classes use a static method to create some basic DIV objects. Here they are: 

// define abstract ‘DivElement’ class
abstract class DivElement{
  private $id;
  private $class;
  private $content;
  abstract public function __construct($content=’This is the
content for the DIV element.’,$id=’divid’,$class=’divclass’);
  abstract public function display();          
}

// define concrete ‘AbsoluteDivElement’ class
class AbsoluteDivElement extends DivElement{
  public function __construct($content=’This is the content for
the DIV element.’,$id=’divid’,$class=’divclass’){
    if(!$content){
      throw new Exception(‘Invalid content for the DIV element’);
    }
    if(strlen($id)>16||!preg_match("/[a-z]/",$id)){
      throw new Exception(‘Invalid ID attribute for the DIV
element.’);
    }
    if(strlen($class)>16||!preg_match("/[a-z]/",$class)){
      throw new Exception(‘Invalid class attribute for the DIV
element.’);
    }
    $this->content=$content;
    $this->id=$id;
    $this->class=$class;     
  }
  public function display(){
    $html='<div';
    if($this->id){
      $html.=’ id="’.$this->id.’"';
    }
    if($this->class){
      $html.=’ class="’.$this->class.’"';
    }
    $html.=’ style="position: absolute;top: 100px;left:
10px;">’.$this->content.'</div>';
    return $html;
  }          
}

// define concrete ‘LeftFloatedDivElement’ class
class LeftFloatedDivElement extends DivElement{
  public function __construct($content=’This is the content for
the DIV element.’,$id=’divid’,$class=’divclass’){
    if(!$content){
      throw new Exception(‘Invalid content for the DIV element’);
    }
    if(strlen($id)>16||!preg_match("/[a-z]/",$id)){
      throw new Exception(‘Invalid ID attribute for the DIV
element.’);
    }
    if(strlen($class)>16||!preg_match("/[a-z]/",$class)){
      throw new Exception(‘Invalid class attribute for the DIV
element.’);
    }
    $this->content=$content;
    $this->id=$id;
    $this->class=$class;     
  }

  public function display(){
    $html='<div';
    if($this->id){
      $html.=’ id="’.$this->id.’"';
    }
    if($this->class){
      $html.=’ class="’.$this->class.’"';
    }
    $html.=’ style="float: left;">’.$this->content.'</div>';
    return $html;
  }          
}

// define concrete ‘RightFloatedDivElement’ class
class RightFloatedDivElement extends DivElement{
  public function __construct($content=’This is the content for
the DIV element.’,$id=’divid’,$class=’divclass’){
    if(!$content){
      throw new Exception(‘Invalid content for the DIV element’);
    }
    if(strlen($id)>16||!preg_match("/[a-z]/",$id)){
      throw new Exception(‘Invalid ID attribute for the DIV
element.’);
    }
    if(strlen($class)>16||!preg_match("/[a-z]/",$class)){
      throw new Exception(‘Invalid class attribute for the DIV
element.’);
    }
    $this->content=$content;
    $this->id=$id;
    $this->class=$class;     
  }

  public function display(){
    $html='<div';
    if($this->id){
      $html.=’ id="’.$this->id.’"';
    }
    if($this->class){
      $html.=’ class="’.$this->class.’"';
    }
    $html.=’ style="float: right;">’.$this->content.'</div>';
    return $html;
  }          
}

// define ‘DivFactory’ class
class DivFactory{
  public static function createDiv($type,$content,$id=’defaultID’,$class=’defaultClass’){
    if($type!=’AbsoluteDivElement’&&$type!
=’LeftFloatedDivElement’&&$type!=’RightFloatedDivElement’){
      throw new Exception(‘Invalid object name for being
created.’);
    }
    return new $type($content,$id,$class);
  }
}

// use ‘DivFactory’ class to spawn some div objects – factory
method is called statically, therefore no factory class instance
is created
try{
  $divs=array(DivFactory::createDiv(‘AbsoluteDivElement’,’This is
the content of the absolutely-positioned DIV
element’),DivFactory::createDiv(‘LeftFloatedDivElement’,’This is
the content of the left-floated DIV
element’),DivFactory::createDiv(‘RightFloatedDivElement’,’This is
the content of the right-floated DIV element’));
  // display divs elements on the browser
  foreach($divs as $div){
    echo $div->display();
  }
}
catch(Exception $e){
  echo $e->getMessage();
  exit();
}

After analyzing the respective signatures of all the classes listed above, possibly you’ll agree with me that using a static method to create DIV objects (or others, of course) is indeed a very effective process, since it allows the spawning of the mentioned objects without having to deal with an instance of the factory class that built them.

So far, so good. Now that you surely recalled all of the hands-on examples developed in the previous article of the series, it’s time to continue exploring the benefits of working with static data in PHP 5. Therefore, in the next section I’ll explain how to create some PHP classes that use static properties, so you can get a better grasp of the idea that stands behind using static members with PHP 5.

To see how these brand new classes will be built, please click on the link that appears below and keep reading.

{mospagebreak title=Defining static properties within PHP 5 classes}

In consonance with the concepts that I explained during the first article of this series, you probably remember the definition of a static property in PHP 5. Just in case you don’t, let me refresh your memory. In crude terms, when a class property is declared static, this means that that it will be unique for the class, and at the same time, its value will be shared by all its eventual instances.

While the previous definition may sound a bit complex at first sight, the truth is that implementing a static property in a useful fashion is a straightforward process that can be performed with minor problems. However, to clarify this rather abstract concept, in the next few lines I’ll build a couple of primitive PHP classes for displaying basic information about some fictional users.

As you’ll see in a moment, these classes will declare a static property inside their API, which will allow different instances of the classes in question to link with each other. But it’s time to finish with the boring theory and see how the classes look, so here are their corresponding signatures:

// define abstract ‘User’ class – declares ‘$nextUserID’ property
static (it can be accessed by all the classes)
abstract class User{
  static public $nextUserID=1;
  public $userID;
  abstract public function __construct($fname,$lname,$email);
  abstract public function getFirstName();
  abstract public function getLastName();
  abstract public function getEmail();
  abstract public function getID();
}

// define ‘ForumUser’ class
class ForumUser extends User{
  public function __construct($fname=’John’,$lname=’Doe’,$email=’john@domain.com’){
    if(!$fname){
      throw new Exception(‘Invalid First Name for forum user.’);
    }
    if(!$lname){
      throw new Exception(‘Invalid Last Name for forum user.’);
    }
    if(!$email||preg_match("/^.+@.+..+$/",$email)){
      throw new Exception(‘Invalid email address for forum
user.’);
    }
    $this->fname=$fname;
    $this->lname=$lname;
    $this->email=$email;
    $this->userID=self::$nextUserID++;
  }

  // get user’s First Name
  public function getFirstName(){
    return $this->fname;
  }

  // get user’s Last Name
  public function getLastName(){
    return $this->lname;
  }

  // get user’s email address
  public function getEmail(){
    return $this->email;
  }

  // get user’s ID
  public function getID(){
    return $this->userID;
  }
}

As you can see, I defined two basic PHP classes. The first one is very convenient for modeling the generic structure of a fictional user, and the second one, "ForumUser," implements all the abstract methods defined by its corresponding parent. So far, this process is quite easy to follow and shouldn’t be difficult to understand at all.

However, I’d like you to focus your attention on the definition of the "$nextUserID" property. In this case, this property has been declared static and also initialized with a value of 1, which means that it can be shared by all the instances created from the base class. Indeed, declaring this property implies that it can be incremented, decremented or whatever you can think of, by the distinct instances of the originating class. This is clearly demonstrated by the definition of the constructor belonging to the "ForumUser" class:

public function __construct($fname=’John’,$lname=’Doe’,
$email=’john@domain.com’){
  if(!$fname){
    throw new Exception(‘Invalid First Name for forum user.’);
  }
  if(!$lname){
    throw new Exception(‘Invalid Last Name for forum user.’);
  }
  if(!$email||preg_match("/^.+@.+..+$/",$email)){
    throw new Exception(‘Invalid email address for forum user.’);
  }
  $this->fname=$fname;
  $this->lname=$lname;
  $this->email=$email;
  $this->userID=self::$nextUserID++;
}

As shown above, each time a new forum user object is created, it takes the value of the static $nextUserID property and increments it, in this way producing a chaining effect across all the user objects. Indeed, the previous sample class very clearly demonstrates how a static property can be shared by several objects in a helpful manner, and it extends the excellent implementation of static data in PHP, provided by Paul Hudson on his web site located at: http://www.hudzilla.org

All right, having said this, I think it’s time to move on and demonstrate how the previous "ForumUser" class can be used in a concrete situation to illustrate the actual functionality of its "$nextUserID" property. So go ahead and visit the following section. I’ll be there, waiting for you.

{mospagebreak title=Demonstrating the functionality of a static property}

As I stated in the previous section, probably the best way to illustrate how the static property belonging to the previous "ForumUser" class can be used is by setting up an example. In this example, some fictional user objects are created, and in consequence, the "$nextUserID" is incremented in each case.

That being explained, here is the corresponding code sample:  

try{
  // create some forum user objects
  $user1=new ForumUser(‘Robert’,’Wilson’,’bob@domain.com’);
  $user2=new ForumUser(‘John’,’Smith’,’johnny@domain.com’);
  $user3=new ForumUser(‘Susan’,’Jackson’,’suse@domain.com’);
  $user4=new ForumUser(‘Mary’,’King’,’mary@domain.com’);  

  // display information on first forum user
  echo ‘<h2>Data for first forum user is as following:</h2>';
  echo ‘<p>First Name: ‘.$user1->getFirstName().'</p><p>Last
Name: ‘.$user1->getLastName().'<p/><p>Email address: ‘.$user1-
>getEmail().'</p><p>User ID: ‘.$user1->getID().'</p>';

  /*
  displays the following:  

  Data for first forum user is as following:

  First Name: Robert
  Last Name: Wilson
  Email address: bob@domain.com
  User ID: 1

  */

  // display information on second forum user
  echo ‘<h2>Data for second forum user is as following:</h2>';
  echo ‘<p>First Name: ‘.$user2->getFirstName().'</p><p>Last
Name: ‘.$user2->getLastName().'<p/><p>Email address: ‘.$user2-
>getEmail().'</p><p>User ID: ‘.$user2->getID().'</p>';

  /*
  displays the following:

  Data for second forum user is as following:

  First Name: John
  Last Name: Smith  
  Email address: johnny@domain.com  
  User ID: 2

  */

  

  // display information on third forum user
  echo ‘<h2>Data for third forum user is as following:</h2>';
  echo ‘<p>First Name: ‘.$user3->getFirstName().'</p><p>Last
Name: ‘.$user3->getLastName().'<p/><p>Email address: ‘.$user3-
>getEmail().'</p><p>User ID: ‘.$user3->getID().'</p>';

  /*
  displays the following:

  Data for third forum user is as following:

  First Name: Susan
  Last Name: Jackson
  Email address: suse@domain.com
  User ID: 3

  */

  // display information on last forum user
  echo ‘<h2>Data for last forum user is as following:</h2>';
  echo ‘<p>First Name: ‘.$user4->getFirstName().'</p><p>Last
Name: ‘.$user4->getLastName().'<p/><p>Email address: ‘.$user4-
>getEmail().'</p><p>User ID: ‘.$user4->getID().'</p>';

  /*
  displays the following:

  Data for last forum user is as following:

  First Name: Mary  
  Last Name: King
  Email address: mary@domain.com
  User ID: 4

  */
}
catch(Exception $e){
  echo $e->getMessage();
  exit();
}

As demonstrated above, after creating some hypothetical forum user objects, their personal data is displayed on the browser via the corresponding accessing methods. Nonetheless, the most interesting thing to note here is how the static $nextUserID" property is incremented each time a new user object is instantiated, in this way showing in a nutshell how the property in question is shared by all the instances of the previous "ForumUser" class.

Finally, as usual with many of my articles on PHP development, feel free to modify the source code of all the sample classes built here. This will help you improve your existing background in using static properties with PHP 5. Happy coding!

Final thoughts

In this second part of the series, I showed you how to define and utilize a couple of PHP classes which incorporate a static property within their API. Nevertheless, this instructive journey isn’t finished yet, since in the last tutorial I’ll teach you how to apply the observer pattern in conjunction with a unique static property to build a data validation system.

The proposal is actually interesting, so I hope to see you there!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye