views:

77

answers:

3

Hello,

think about an array like this:

...
"key1" => some_call("val1", $params),
"key2" => some_call("val1", $params),
...

now i want to pass parameters ($params) when addressing my array entries

$x = $array['key1'] , $params ... 

is there some way to do something like this?

UPDATE

why would i like to do this? i am using codeigniter and in the language file is an assoc array, where the right side holds the text in its predicted language. i want to abuse this a little bit and want to load email templates, where i pass a parameter which holds the values which shell be replaced in the template.

UPDATE 2

for php 5.2.*

+1  A: 

Make $x an array?

$x[] = $array['key1'] , $params ... 

or

$x = array($array['key1'] , $params ... )

or a concatenated string

$x = $array['key1'] . $params ... // use the . to concat
Phill Pafford
+4  A: 

Since PHP 5.3 you can use anonymous functions. Maybe you want something like this:

<?php

function some_call($arg,$params)
{
     echo "$arg: ",count($params),"\n";
}

$array = array(
    'key1' => function($params) { some_call('val1',$params); },
    'key2' => function($params) { some_call('val1',$params); }
);

$array['key1'](array(1,2,3));
giftnuss
oooh nooo :-) does not work in php 5.2.1 ??
helle
can i install/plugin that feature on a 5.2.1 version, anyway?
helle
You could use `create_function` but you **will not**. Or you could defined normal non-lambda functions. Another variant is compiling the PHP 5.3 source to PHP 5.2 source using [prephp](http://github.com/nikic/prephp). But I don't think that this is already stable enough.
nikic
use `eval` instead
Petah
+2  A: 

Instead of anonymous functions (i.e. if you're using PHP5 < 5.3) then you could use the create_function() function to achieve what you want:

function some_call($arg, $params)
{
     echo $arg, ': ', count($params), "\n";
}

$array = array(
    'key1' => create_function('$params', 'some_call("val1", $params);'),
    'key2' => create_function('$params', 'some_call("val2", $params);'),
);

$array['key1'](array(1,2,3));
Nev Stokes
for use in real code: 'key1' => create_function('$params', 'return some_call("val1", $params);'). then i can directly access the result
helle