PHP 默认函数参数作为 T_VARIABLE?

标签 php function arguments

我正在尝试提供一个成员变量作为类方法的默认值。

我知道不可能将变量用作非类函数的默认值,但似乎应该有一种方法可以在类中执行此操作。

一定有办法做到这一点 - 也许我只是语法错误:

class test{
  private $test = '';

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

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

但这会抛出一个错误:

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

有什么想法吗?

最佳答案

来自manual :-

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

我可能只会做类似的事情:-

<?php

class Test {

    public function __construct() {

        $this->test = "whatever";

    }

    public function getTest($var=NULL) {

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

        echo $var;
    }
}
?>

关于PHP 默认函数参数作为 T_VARIABLE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224014/

相关文章:

php - 如何下载包含 HTML 标签的 csv 文件

javascript - 基于传入参数的计算器函数

c++ - 使用::访问类函数

Android 内容解析器查询占位符整数

javascript - toString 参数是什么?

javascript - 在php中完成表单提交后是否可以重定向回来?

php - 没有为表单中的文件创建目录

php - xml 集成 - 将 xml 发布到 url

python - 如何在函数中使用 *args 返回字典列表?

c - 在不同的 .c 文件中使用函数(c 编程 101)