Jump to content

Static variables in a class


php_guy

Recommended Posts

Hello!

 

How could I have a static member variable inside a class?

// common.php
class my_class 
{
    $flag = true;
}

So that later, I can use it in the following manner:

 

// some other file

require_once("common.php");

if( my_class::flag == true ) {
}

 

Thanks!

 

Link to comment
Share on other sites

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
    }
}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.