用于存储函数数组的PHP静态变量

时间:2021-09-25 15:40:12

I am trying to store all the attribute predicates within a static array in PHP:

我正在尝试在PHP的静态数组中存储所有属性谓词:

public static $attributeValidation = [
    "attribute1" => function ($value) {
        return is_bool($value);
    },"attribute2" => function ($value) {
        return is_int($value);
    },
];

I am getting this following error:

我得到以下错误:

expression is not allowed as default field value.

The goal is to simplify attribute validation by using

目标是通过使用来简化属性验证

$attributeValidation["attribute"]($someValue);

Is there a way to accomplish this without using a local/private variables?

是否有一种方法可以在不使用本地/私有变量的情况下实现这一点?

1 个解决方案

#1


4  

Is there a way to accomplish this without using a local/private variables

是否有一种方法可以在不使用本地/私有变量的情况下实现这一点

Yes. Simply create static method which would return the array you need:

是的。只需创建静态方法,返回所需的数组:

public static function getAttributeValidation(): array
{
   return [
       // populate your array as you like
       ...
   ];
}

and then in your code instead of SomeClass::$attributeValidation you will do SomeClass::getAttributeValidation() to get that array.

然后在代码中,而不是SomeClass: $attributeValidation中,您将执行SomeClass:::getAttributeValidation()来获取该数组。

#1


4  

Is there a way to accomplish this without using a local/private variables

是否有一种方法可以在不使用本地/私有变量的情况下实现这一点

Yes. Simply create static method which would return the array you need:

是的。只需创建静态方法,返回所需的数组:

public static function getAttributeValidation(): array
{
   return [
       // populate your array as you like
       ...
   ];
}

and then in your code instead of SomeClass::$attributeValidation you will do SomeClass::getAttributeValidation() to get that array.

然后在代码中,而不是SomeClass: $attributeValidation中,您将执行SomeClass:::getAttributeValidation()来获取该数组。