PHP default function argument as a T_VARIABLE?

后端 未结 2 688
清酒与你
清酒与你 2021-01-20 22:27

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

相关标签:
2条回答
  • 2021-01-20 22:42

    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 讨论(0)
  • 2021-01-20 22:52

    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;
        }
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题