0

For example I have the following:

public function foo($integer = 1; $myObj = new myClass()){}

"Parse error: syntax error, unexpected 'new' (T_NEW) in C:\xampp\htdocs..."

user3646717
  • 1,095
  • 2
  • 12
  • 21
  • because its not valid php - what else to say? –  Aug 31 '16 at 03:54
  • you can set it as `myClass $myObj`, just like the answer below, so that you can pass an instance of that class in your argument – Kevin Aug 31 '16 at 03:59

1 Answers1

1

The function prototype has to be evaluated at compile time. There's no way to know what new myClass is until you're in the runtime, because we need the definition of the class and all of its ancestors to be able to build it plus any additional runtime information required to do so.

You can still set the default argument in your function though so that the assignment is deferred to the runtime.

class myClass {
    public function foo($integer = 1, myClass $myObj = null) {
        if (!$myObj) {
            $myObj = new myClass;
        }
    }
}

Also note you have a syntax error in your function prototype. The argument separator is a comma , and not a semicolon ;.

Sherif
  • 11,786
  • 3
  • 32
  • 57