【问题标题】:Class instance without variable没有变量的类实例
【发布时间】:2011-05-25 03:33:59
【问题描述】:

我想要解决的问题是实例化一个像这样的类是不好的做法

new Classname();

因为我需要运行类 __construct 但我不需要使用该类。因为类中的其他函数将从 __construct 中调用。

【问题讨论】:

  • 为什么你想这样做?听起来您几乎是在设置单例的默认值..
  • 构造函数的唯一职责是准备对象以供使用。除此以外,它不能做任何事情,也不能有副作用。实际上,将所有对象的行为都放在构造函数中是一种不好的做法。当然也有例外,但如果你的类不需要析构函数,那么你就没有遇到这样的例外。

标签: php


【解决方案1】:

它会起作用,但是,作为维护您的代码的人,我会对此感到非常困惑。一般来说,仅仅实例化一个对象没有副作用,所以我假设我可以删除那行,一切仍然可以正常工作。

我建议重新考虑您的代码结构,因为将带有副作用的代码放在 __construct 中绝对不标准。

【讨论】:

  • 类在全局范围内的干净输入中做了什么,所以它并不真的需要一个变量.. 那么将变量放在那里仍然值得吗?
  • 克里斯,只是为了更容易理解。
  • @Chris R,更好的解决方案是$input = new InputFilter($_POST),然后使用$input['foo'] 而不是$_POST['foo']。如果不使用$_POST,您可能会有类似$globalfoo = new InputFilter($globalfoo) 的内容。在函数内部使用全局变量(global 关键字)本身几乎总是一种不好的做法。
【解决方案2】:

考虑改用这样的东西:

class Foo
{
  public static function do_something()
  {
     // ...
  }
}

Foo::do_something();

虽然你所拥有的东西会起作用,但不清楚是否应该发生某些事情。

(如果你坚持要这样使用对象,至少每次这样做时都要清楚地记录下来。)

【讨论】:

  • 这也是可能的,而且可能比某些变量更多。看起来,如果您将逻辑移至 __construct,您的代码在这里比 OOP 更实用。
【解决方案3】:

好吧,假设我们有一个名为 HelloWorld 的类名到一个文件中。

文件class.HelloWorld.php

class HelloWorld {

   function __construct()
   {
   }

   public function doSomething(){
       echo "new HelloWorld()->doSomething() was called";
   }

   public function anotherMethod(){
       echo "new HelloWorld()->anotherMethod() was called";
   }
}

现在您可以在运行时实例化该类,而无需将其保存到变量中。

require('class.HelloWorld.php');
// you can just instantiate it and the constructur will be called automatically 
(new HelloWorld());

// or you can instantiate it and call other methods
(new HelloWorld())->doSomething();

我不确定垃圾收集器是否会删除实例化的类,但我假设因为这些类没有保存到变量中,所以它不会保存在内存中的某个地方,那将是完美的。

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 2021-05-09
    • 2014-12-27
    • 2012-04-10
    • 1970-01-01
    • 2013-03-24
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多