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! Link to comment https://forums.phpfreaks.com/topic/58603-static-variables-in-a-class/ 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 } } Link to comment https://forums.phpfreaks.com/topic/58603-static-variables-in-a-class/#findComment-290675 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"; } ?> Link to comment https://forums.phpfreaks.com/topic/58603-static-variables-in-a-class/#findComment-290788 Share on other sites More sharing options...
php_guy Posted July 6, 2007 Author Share Posted July 6, 2007 Thanks guys! Link to comment https://forums.phpfreaks.com/topic/58603-static-variables-in-a-class/#findComment-291403 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. Link to comment https://forums.phpfreaks.com/topic/58603-static-variables-in-a-class/#findComment-291414 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.