简体   繁体   English

在foreach循环中使用PHP常量

[英]Using of PHP constants in foreach loop

I need to use PHP contants in foreach loop: 我需要在foreach循环中使用PHP竞争者:

define('WEBS', 'http://google.com, http://yahoo.com');
foreach (WEBS as $a) {
    //do something
}

However I managed to do that by following code, although it works fine but aptana editor shows syntax error. 但是我设法通过以下代码做到了这一点,尽管它可以正常工作,但aptana编辑器显示语法错误。 Please guide me how to do that in the correct manner. 请指导我如何正确进行操作。

foreach (get_defined_constants(true)['user']['WEBS'] as $w) {
//do something
} 

You have to explode the values first 您必须先explode

foreach (explode(', ', WEBS) as $url) { ...

explode() will break a string into an array so that you can iterate through it explode()会将字符串分解为数组,以便您可以迭代它


Alternatively, you could even use preg_split . 另外,您甚至可以使用preg_split

foreach(preg_split('/,\s*/', WEBS) as $url) { ...

preg_split() allows you to split your string based on a regular expression. preg_split()允许您基于正则表达式拆分字符串。 It returns an array. 它返回一个数组。 As an example, using this regex, the space following the comma is optional. 例如,使用此正则表达式,逗号后的空格是可选的。

# a string like this
foo.com, hello.com,world.com,  test.com

# would still split properly to
[
  'foo.com',
  'hello.com',
  'world.com',
  'test.com'
]

Regex methods are not always necessary. 正则表达式方法并不总是必需的。 But I thought I'd show you that a little more control is available when it's necessary. 但我想我会告诉您,在必要时可以使用更多控件。


Aptana is showing you an error because you can't use [] after a func() prior to PHP 5.4. Aptana向您显示错误,因为您不能在PHP 5.4之前的func()之后使用[] To get around that, you can do things like: 为了解决这个问题,您可以执行以下操作:

$constants = get_defined_constants(true);
$constants['user']['WEBS'];

But in this case WEBS should be just fine. 但是在这种情况下, WEBS应该就可以了。 The only issue you were having is that you needed to convert the string to an array first. 您遇到的唯一问题是,您需要首先将字符串转换为数组。

Looks like misuse of constants. 看起来像是滥用常数。

It seems you need a regular variable of array type. 似乎您需要一个数组类型的常规变量。

$webs = array('http://google.com', 'http://yahoo.com');
foreach ($webs as $a) {
    //do something
}

If you still thinks that constants is what you need - better ask another question, explaining why so, and be told of what you're doing wrong 如果您仍然认为常量是您所需要的-最好再问一个问题,解释原因,然后告知您做错了什么

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

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