php_guy Posted July 5, 2007 Share Posted July 5, 2007 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! Quote Link to comment Share on other sites More sharing options...
per1os Posted July 5, 2007 Share Posted July 5, 2007 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 } } Quote Link to comment Share on other sites More sharing options...
trq Posted July 5, 2007 Share Posted July 5, 2007 <?php class foo { static $bar = true; } if (foo::$bar) { echo "true"; } ?> Quote Link to comment Share on other sites More sharing options...
php_guy Posted July 6, 2007 Author Share Posted July 6, 2007 Thanks guys! Quote Link to comment Share on other sites More sharing options...
roopurt18 Posted July 6, 2007 Share Posted July 6, 2007 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.