Jump to content

Syntax error when using new in constructor parameter


betonboor

Recommended Posts

Hi,

 

I'm new here and got a very specific PHP question. I got the following code:

 

<?php

class Foo {

}

class Bar {
private $foo;
private $string;
public function __construct( $string = 'abc', $foo = new Foo() ) {
	$this->string = $string;
	$this->foo = $foo;
}
}

$bar = new Bar();

?>

 

It gives me an "unexpected T_NEW" syntax error for the line

 

public function __construct( $string = 'abc', $foo = new Foo() ) {

 

I know I can use something like this, although it's a rather ugly workaround:

public function __construct( $string = 'abc', $foo = null ) {
if( is_null($foo) ) {
	$foo = new Foo();
}
$this->string = $string;
$this->foo = $foo;
}

 

But my question is, why is it not allowed to create a new object as a default for a parameter in the constructor?

 

Thanks in advance!  :)

Link to comment
Share on other sites

You can't have $foo = new Foo()

 

Try this:

 

public function __construct( $string = 'abc', $foo = null ) {
	if($foo == null)
		$foo = new Foo();
	$this->string = $string;
	$this->foo = $foo;
}

 

Thanks, I know that works and does the job perfectly fine :), but that doesn't really answer my original question:

 

Why is it not allowed? Why can I initiate primitives in parameters but cannot create objects? Is there a specific technical reason? Or perhaps it's just a bug? I'd like to know :D

Link to comment
Share on other sites

parameters can not do anything except hold values, yours would then try to run the constructor of the class Foo, and a parameter is not allowed to do that.

 

Thank you very much! :)

 

Instead of creating an object, I've tested a function call as a parameter. Indeed I get a similar syntax error, unexpected '('.

It appears that parameters apparently cannot run code, probably by design. It actually kind of makes sense now :P

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.