假设我有以下类(class):
class Test
{
function __construct()
{
// initialize some variable
$this->run();
}
function run()
{
// do some stuff
$this->handle();
}
function handle()
{
}
}
通常我会创建一个像这样的实例:
$test = new Test();
但是我真的不需要 $test
任何地方,因为类中的函数一次完成所有工作,之后我将不再需要类的实例。
在这种情况下我应该做什么或者我应该做什么:$test = new Test();
我希望我想说的是有道理的,如果没有请告诉我。
最佳答案
如果不需要实例化的实例,它们可能应该是静态函数:
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();
关于php - 在 PHP 中使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7125585/