Jump to content

Static variables in a class


php_guy

Recommended Posts

It depends if you are using php 5 it should look something like this:

 

<?php
class my_class 
{
    public $flag = true;
}

 

or php 4

 

<?php
class my_class 
{
    var $flag;

    function my_class() {
          $this->flag = true; // instantiate the variable
    }
}

Consider taking it one step further and using a static function in combination with a static variable:

 

<?php
  class foo {
    static $bar = true;

    public static function performTest(){
      return foo::$bar;
    }
  }

  if (foo::performTest()) {
    echo "true";
  }
?>

 

The benefit is not apparent until you decide that a simple flag is not enough to determine the condition.  In the future, you may have to compare $bar with multiple values or perform additional logical operations.  Should that occur, you will have to go through all of your code and update your conditionals that are testing the value foo::$bar.

 

However, if you wrap the test inside of a static method and later decide to change the test, you only have to change it in one place and all of your code will continue to work.

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.