开发者

PHP default function argument as a T_VARIABLE?

开发者 https://www.devze.com 2022-12-20 01:09 出处:网络
I\'m trying to provide a member variable as a default value for a class method. I know it\'s impossible to use a variable as a default value for a non-class function, but it seems like there should b

I'm trying to provide a member variable as a default value for a class method.

I know it's impossible to use a variable as a default value for a non-class function, but it seems like there should be a way to do this within a class.

There must be a 开发者_StackOverflow社区way to do it - perhaps I just have the wrong syntax:

class test{
  private $test = '';

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

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

but this throws an error saying something like:

$this->test as a function argument default value is not allowed. unexpected T_VARIABLE.

Any thoughts?


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;
    }
}
?>


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号