3

Possible Duplicate:
PHP class instantiation. To use or not to use the parenthesis?
Omission of brackets and parameter-less object constructors

With or without the brackets, the new Class seems not bother. So, I doubt what's the usage of the brackets (). I searched php manual, didn't get it. Could anybody explain?

Community
  • 1
  • 1
Jenny
  • 1,729
  • 4
  • 19
  • 37

1 Answers1

9

The purpose of the brackets is for you to enter any arguments that your constructor may accept.

class Example{

    private $str;

    public function __construct($str){
        $this->str = $str;
    }

    public function output(){
        echo $this->str;
    }

}

$ex = new Example; // missing argument error
$ex = new Example('Something');
$ex->output(); // echos "Something"

If your class constructor does not accept any arguments, you may leave the brackets out. For good code sake, I always keep the brackets, whether or not the constructor accepts any argument.

Most coders coming from C# or Java background would keep the parenthesis as it is more familar to them.

mauris
  • 42,982
  • 15
  • 99
  • 131
  • I don't see why i was downvoted trying to answer the asker's question. – mauris Feb 17 '12 at 09:12
  • I really appreciate your answer and other experts that helped me on my php journey. Sometimes it's hard to understand why got down vote without a tip pointing any mistake. I will keep the question open for a little while to see if the person who vote down your answer has anything else to say. – Jenny Feb 17 '12 at 09:18
  • I did not downvote but i would argue its good code to omit them: less cruft. – Gordon Feb 17 '12 at 09:21
  • 1
    I see, Gordon, the arrow is for voting. For different opinion, you can post a new answer. Thanks for explain anyway :-) – Jenny Feb 17 '12 at 09:25
  • 1
    @Jenny I've already answered this in one of the linked duplicates – Gordon Feb 17 '12 at 10:26