Let's say I have got the following class:
class Test
{
function __construct()
{
// initialize some variable
$this->run();
}
function run()
{
// 开发者_如何学JAVAdo some stuff
$this->handle();
}
function handle()
{
}
}
Normally I would create an instance like:
$test = new Test();
However I don't really need the $test
anywhere since the functions in the class do all the work once and after that I won't need the instance of the class anymore.
What should I do in this situation or should I just do: $test = new Test();
I hope it makes sense what I'm trying to say if not please tell me.
They should probably be static functions, if they don't require an instantiated instance:
class Test
{
private static $var1;
private static $var2;
// Constructor is not used to call `run()`,
// though you may need it for other purposes if this class
// has non-static methods and properties.
// If all properties are used and discarded, they can be
// created with an init() function
private static function init() {
self::$var1 = 'val1';
self::$var2 = 'val2';
}
// And destroyed with a destroy() function
// Make sure run() is a public method
public static function run()
{
// Initialize
self::init();
// access properties
echo self::$var1;
// handle() is called statically
self::handle();
// If all done, eliminate the variables
self::$var1 = NULL;
self::$var2 = NULL;
}
// handle() may be a private method.
private static function handle()
{
}
}
// called without a constructor:
Test::run();
If you don't need it, just do:
new Test();
You can just call it like this (new Test()).functionHere()
. Alternativly you could just make the function static and do Test::functionHere()
None of those is required. Even if you keep the $test variable that won't change anything because it won't take even a 0,001% of the RAM memory. Just continue the program's flow. The best answer from the above is to initiate the class without saving an instance in a variable. Bet even if you do that won't change anything. If I were you, I was going to leave that variable, because later I if I add another function which needs to be called manually that would be the easiest way to call it.
Assigning a value is not required, it will work as
new Test;
Alternativly, you can write your class in static format:
class Test
{
public static function run()
{
// do some stuff
self::handle();
}
public static function handle()
{
}
}
And call your class as:
Test::run();
精彩评论