开发者

Class instance without variable

What i am trying to work out is it bad practice instantiate a class like

new Classname();

As i need to run the classes __construct but i do not need to use the class past that. as other functions within the class will be called from the开发者_JS百科 __construct.


It'd work, but, as someone maintaining your code, I'd be super confused by that. Generally, merely instantiating an object has no side-effects, so I'd assume that I could just delete that line and everything would still work fine.

I'd recommend reconsidering your code's structure, since putting code with side-effects in __construct is definitely not standard.


Consider using something like this instead:

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

Foo::do_something();

While what you've got will work, it isn't clear that something is supposed to happen.

(If you insist upon using the object like that, at least document it clearly whenever you do that.)


Well let just say that we have a classname called HelloWorld into a file.

File 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";
   }
}

Now you can instantiate the class on runtime without saving it into a variable.

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();

I'm not sure if the garbage collector will delete the instantiated classes or not, but i assume since those classes are not saved into a variable this would not be saved somewhere in the memory and that would be perfect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜