【问题标题】:Pass function in static variable of class PHP在 PHP 类的静态变量中传递函数
【发布时间】:2019-08-17 17:28:03
【问题描述】:

我有一个带有静态变量的类:

 class MyClass {
    protected static $rules = [
         'name' => 'required'
         'help' => 'required|in:' . implode(',', custom_helper_function());
    ];
 }

我想在这个变量中使用自定义辅助函数并使用 implode。我该怎么做?现在我得到错误:

expression is not allowed as field default value

谢谢。

【问题讨论】:

  • 你在使用任何框架吗?
  • @SaadSuri 是的.. Laravel
  • 嗯... PHP 告诉你,你不能,但是here's a possible workaround.
  • 你不能在构造函数/函数之外的php中设置成员或类变量的默认值。这就是 php 抛出此错误的原因。将初始化代码移动到构造函数或其他静态类方法。这是一个类似的问题:stackoverflow.com/a/35037631/1345973
  • @HichemBOUSSETTA 这不是真的。它是静态的,所以他想在不创建类实例的情况下使用它。

标签: php


【解决方案1】:

您不能在变量定义上使用函数。如果它只是一个普通的,我建议你在构造函数上分配值,但是作为一个静态的,那是不可能的/没有意义。

那你就做不到。尽管您可以使用静态函数实现类似的功能:

 class MyClass {

    public static function getRules() {
        $rules = [
         'name' => 'required',
         'help' => ( 'required|in:' . implode(',', custom_helper_function()) )
        ];
        return $rules;
    }
 }
 MyClass::getRules();

另外,不要忘记定义 custom_helper_function。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多