PHP 默认函数参数作为 T_VARIABLE? [英] PHP default function argument as a T_VARIABLE?

查看:22
本文介绍了PHP 默认函数参数作为 T_VARIABLE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 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 作为函数参数默认值是不允许的.意外的 T_VARIABLE.

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

有什么想法吗?

推荐答案

来自 手册:-

默认值必须是常量表达式,而不是(例如)a变量、类成员或函数打电话.

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

这篇关于PHP 默认函数参数作为 T_VARIABLE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆