在PHP中使用类
假设我有以下课程:在PHP中使用类,php,class,Php,Class,假设我有以下课程: class Test { function __construct() { // initialize some variable $this->run(); } function run() { // do some stuff $this->handle(); } function handle() { } } 通常
class Test
{
function __construct()
{
// initialize some variable
$this->run();
}
function run()
{
// do some stuff
$this->handle();
}
function handle()
{
}
}
通常我会创建一个实例,如:
$test = new Test();
然而,我并不真正需要$test
,因为类中的函数只做了一次所有的工作,之后我就不再需要类的实例了
在这种情况下,我应该做什么,还是干脆做:$test=newtest()代码>
我希望我想说的有道理,如果不是,请告诉我。如果它们不需要实例化实例,它们可能应该是静态函数:
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();
如果您不需要它,只需执行以下操作:
new Test();
您可以这样调用它(newtest()).functionHere()
。或者,您可以将函数设置为静态,然后执行Test::functionHere()
这些都不是必需的。即使保留$test变量,也不会改变任何内容,因为它甚至不会占用0001%的RAM内存。继续程序的流程。上面给出的最佳答案是在不将实例保存在变量中的情况下初始化类。打赌即使你这样做也不会改变任何事情。如果我是你,我会留下这个变量,因为以后如果我添加另一个需要手动调用的函数,这将是调用它的最简单方式。不需要赋值,它将按如下方式工作
new Test;
或者,您可以用静态格式编写类:
class Test
{
public static function run()
{
// do some stuff
self::handle();
}
public static function handle()
{
}
}
并将您的班级命名为:
Test::run();
我也这么认为。但是,我应该在何处/如何初始化现在在构造函数中发生的变量。(PS类中的其他函数应该可以访问这些变量)@PeeHaa参见上面的添加。静态属性在init()
方法中初始化,并在调用handle()
后设置为NULL。也可以在handle()中移除它们。
太棒了!谢谢为什么要在完成后删除变量?@PeeHaa由于变量是静态的,它们由类Test
的所有实例共享,并且可能在内存中挂起以执行脚本。如果你不想在一个页面上这样做不止一次,不要担心会破坏它们。/@Itehnological更该死的东西你的名字太长了:我担心的不是性能/内存。我只是想知道在这种情况下最好的做法是什么。谢谢你的回答:)(新测试()).functionHere()
以前从未见过这种风格。它叫什么,我可以在文档中查找它。我不知道它是否有正式名称,但基本上你创建的对象没有引用它。Asnew Test()
返回一个新的测试对象,该对象已准备好使用。因此,通过将其包装在()
中,您可以灵活地使用对象的方法