views:

127

answers:

3

Got an error today that I thought was interesting. Must be a way to do this, perhaps I just have the wrong syntax.

class test{
  private $test = '';

  __construct(){
    $this->test = "whatever";
  }

  function getTest($var = $this->test){
    echo $var;
  }

}

This throws an error basically saying that $this->test as a function argument default value is not allowed. unexpected T_VARIABLE.

Now I know for a function not inside of a class, it would be impossible to grab a default value that is another string, but it seems like there should be a way to do this within a class.

Any thoughts?

+2  A: 

I believe you can only use constants (strings, numbers, etc) in that syntax (but I could be wrong about that).

I suggest this alternative:

function getTest($var = null) {
    if (is_null($var)) {
        $var = $this->test;
    }
}
Matt
+1  A: 

The php5 syntax for contructor is not construction()

function __construct() {

}
Yada
+5  A: 

From the manual:-

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

I'd probably just do something like:-

<?php

class Test {

    public function __construct() {

        $this->test = "whatever";

    }

    public function getTest($var=NULL) {

        if (is_null($var)) {
            $var = $this->test;
        }

        echo $var;
    }
}
?>
Gavin Gilmour