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!  :)

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.