使用 array_map 调用数组中对象的方法?
假设我有一个简单的类,例如:
class MyClass {
private $_prop;
public function getProp() {return $this->_prop;}
[....]
}
现在我想要在不在 MyClass
范围内的地方做的是从 MyClass
($objs
)。这当然可以用这样的代码来完成:
$props = array();
foreach ($objs as $obj) {
$props[] = $obj->getProp();
}
但是这需要引用一些行,特别是当以这种方式格式化时(并且我必须使用这样的格式)。所以问题是:是否可以使用 array_map 来做到这一点?一种方法是使用 create 函数,但我不太喜欢 php 中的那样(php 中的 lambda 至少很尴尬,如果我理解正确的话,它的性能就像评估代码的性能一样,但性能不是这里的重点)。我已经厌倦了搜索,但未能找到任何明确的答案。但我总有一种感觉,这是不可能的。我尝试了诸如 array_map(array('MyClass', 'getProp'), $objs)
之类的方法,但这不起作用,因为方法不是静态的。
编辑:我正在使用 php 5.3。
Suppose I have simple class like:
class MyClass {
private $_prop;
public function getProp() {return $this->_prop;}
[....]
}
Now what I want to do somwhere not in scope of MyClass
is to get array of $_prop from array of objects of MyClass
($objs
). This of course can be done with code like this:
$props = array();
foreach ($objs as $obj) {
$props[] = $obj->getProp();
}
However this takes quote some lines, esp when formated in this way (and I have to use such formatting). So question is: if it is possible to do this using array_map? One way would be to use create function, but I don't really like that in php(lambdas in php are at least awkward and if i understand correctly its performance is like that of evaled code, but performance is beside the point here). I have tired searching quite a bit and failed to find any definetive answer. But I kinda have a feeling that it's not possible. I tried things like array_map(array('MyClass', 'getProp'), $objs)
, but that does not work since method is not static.
Edit: I'm using php 5.3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 PHP 5.3 中,您可以执行以下操作:
(请参阅匿名函数)
当然,这仍然比使用 for 循环慢,因为每个元素都有一个函数调用,但我认为这最接近您想要的。
或者,它也适用于 PHP 5.3 之前的版本,并且可能更适合您的风格指南:
或者(再次回到 PHP 5.3)您可以创建一个像这样的包装函数(但这将是我认为最慢的可能性):
In PHP 5.3 you can do:
(see anonymous functions)
Of course this will still be slower than using a
for
loop as you have one function invocation per element but I think this comes closest to what you want.Alternatively, which also works in prior to PHP 5.3 and might fit better to your style guidelines:
Or (again back to PHP 5.3) you could create a wrapper function like this (but this will be the slowest possibility I think):