design patterns - Running code in a PHP once -
i'm trying write class in php acts wrapper collection of command line tools make them easier use php.
i have single class (myclass
) in file myclass.php
.
i have code checks see if required tools installed , sets constant (tools_available
) either true
or false
. although it's not lot of code, want run first time tries instantiate class or use of static functions. what's best practice handling this?
i want run first time tries instantiate class or use of static functions.
well, best answer not have static methods. can stick code in constructor method per answer @treegarden.
if must have static methods, you'll need static flag within class indicate when you've called 'run once' code, can avoid running again. , call explicitly each of static methods , constructor. this:
<?php class myclass { private static $hasrunonce = false; private static runmeonce() { if (!self::$hasrunonce) { self::$hasrunonce = true; //put 'run once' code here... } } public static oneofyourstaticmethods() { self::runmeonce(); //put static method code here... //this same each of static methods , constructor. } }
hope helps.
Comments
Post a Comment