简体   繁体   English

in_array 不适用于类常量

[英]in_array does not work with class constants

I have a problem with in_array using newly introduced array class constants.我在使用新引入的数组类常量时遇到了 in_array 问题。 When I put a class constant which contains an array into the function I get a warning:当我将包含数组的类常量放入函数时,我收到警告:

Warning: in_array() expects parameter 2 to be array, unknown given in...

Code:代码:

foreach ($fields as $key => $value) {
    if (in_array($key, self::FIELDS)) $this->$key = $value;
}

Constant (inside a class):常量(在类内):

const FIELDS = [
    self::FIELD_ID,
    self::FIELD_STREET,
    self::FIELD_HOUSE_NR,
    self::FIELD_POSTCODE,
    self::FIELD_CITY,
    self::FIELD_PERSONAL_NUMBER,
    self::FIELD_SELLER_NAME,
    'empty'
];

The weirdest part of this problem is that it works on my local machine without any errors/warnings (Mac) running PHP 5.6.2 but does not on my server also running PHP 5.6.2.这个问题最奇怪的部分是它在我的本地机器上运行 PHP 5.6.2 没有任何错误/警告 (Mac) 但在我的服务器上运行 PHP 5.6.2 时却没有。

How do I resolve this error?如何解决此错误? (I don't want to use static arrays...) (我不想使用静态数组...)

The root problem is class constants can't be arrays (unless it's php 5.6 or greater as pointed out by bluefirex).根本问题是类常量不能是数组(除非 bluefirex 指出它是 php 5.6 或更高版本)。 PHP Constants Containing Arrays? PHP 常量包含数组? http://php.net/manual/en/language.oop5.constants.php http://php.net/manual/en/language.oop5.constants.php

On PHP 7.2 and in_array returned FALSE with a class constant array, at least in my case...在 PHP 7.2 和 in_array 返回FALSE和类常量数组,至少在我的情况下......

I used this as a workaround:我用它作为解决方法:

if(isset(self::MAPPING_OLD_REFS[$sku]))  $sku = self::MAPPING_OLD_REFS[$sku];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM