Passing named parameters to a php function through call_user_func_array - php

When trying to call a function in a child class with an arbitrary set of parameters, I'm having the following problem:
class Base{
function callDerived($method,$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test($foo,$bar){
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2','foo'=>1));
Outputs:
foo=2, bar=1
Which... is not exactly what I wanted - is there a way to achieve this beyond re-composing the array with the index order of func_get_args? And yes, of course, I could simply pass the whole array and deal with it in the function... but that's not what I want to do.
Thanks

No. PHP does not support named parameters. Only the order of parameters is taken into account. You could probably take the code itself apart using the ReflectionClass to inspect the function parameter names, but in the end you'd need to use this to reorder the array anyway.

The stock PHP class ReflectionMethod is your friend.
Example:
class MyClass {
function myFunc($param1, $param2, $param3='myDefault') {
print "test";
}
}
$refm = new ReflectionMethod('MyClass', 'myFunc');
foreach ($refm->getParameters() as $p)
print "$p\n";
And the result:
Parameter #0 [ <required> $param1 ]
Parameter #1 [ <required> $param2 ]
Parameter #2 [ <optional> $param3 = 'myDefault' ]
At this point you know the names of the parameters of the target function. With this information you can modify your method 'callDerived', and you can re-order the array to call_user_func_array according to the parameter names.

Good news, I had the same concern (I was looking for named arguments in PHP, like Python does), and found this useful tool : https://github.com/PHP-DI/Invoker
This uses the reflection API to feed a callable with some arguments from an array and also use optional arguments defaults for other parameters that are not defined in the array.
$invoker = new Invoker\Invoker;
$result = $invoker->call(array($object, 'method'), array(
"strName" => "Lorem",
"strValue" => "ipsum",
"readOnly" => true,
"size" => 55,
));
Have fun

UPDATE: PHP 8 Now supports named parameters. And it works with call_user_func_array if you pass an associative array. So you can simply do this:
<?php
function myFunc($foo, $bar) {
echo "foo=$foo, bar=$bar\n";
}
call_user_func_array('myFunc', ['bar' => 2, 'foo' => 1]);
// Outputs: foo=1, bar=2
In your code, you'll be happy to know that you don't have to change a thing. Just upgrade to PHP 8 and it'll work as you expected

You can simply pass an array and extract:
function add($arr){
extract($arr, EXTR_REFS);
return $one+$two;
}
$one = 1;
$two = 2;
echo add(compact('one', 'two')); // 3
This will extract as references, so there is close to no overhead.

I use a bitmask instead of boolean parameters:
// Ingredients
define ('TOMATO', 0b0000001);
define ('CHEESE', 0b0000010);
define ('OREGANO', 0b0000100);
define ('MUSHROOMS', 0b0001000);
define ('SALAMI', 0b0010000);
define ('PEPERONI', 0b0100000);
define ('ONIONS', 0b1000000);
function pizza ($ingredients) {
$serving = 'Pizza with';
$serving .= ($ingredients&TOMATO)?' Tomato':'';
$serving .= ($ingredients&CHEESE)?' Cheese':'';
$serving .= ($ingredients&OREGANO)?' Oregano':'';
$serving .= ($ingredients&MUSHROOMS)?' Mushrooms':'';
$serving .= ($ingredients&SALAMI)?' Salami':'';
$serving .= ($ingredients&ONIONS)?' Onions':'';
return trim($serving)."\n" ;
}
// Now order your pizzas!
echo pizza(TOMATO | CHEESE | SALAMI);
echo pizza(ONIONS | TOMATO | MUSHROOMS | CHEESE); // "Params" are not positional

For those who still might stumble on the question (like I did), here is my approach:
since PHP 5.6 you can use ... as mentioned here:
In this case you could use something like this:
class Base{
function callDerived($method,...$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test(...$params){
foreach ($params as $arr) {
extract($arr);
}
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2'),array('foo'=>1));
//print: foo=1, bar=2

There is a way to do it and is using arrays (the most easy way):
class Test{
public $a = false;
private $b = false;
public $c = false;
public $d = false;
public $e = false;
public function _factory(){
$args = func_get_args();
$args = $args[0];
$this->a = array_key_exists("a",$args) ? $args["a"] : 0;
$this->b = array_key_exists("b",$args) ? $args["b"] : 0;
$this->c = array_key_exists("c",$args) ? $args["c"] : 0;
$this->d = array_key_exists("d",$args) ? $args["d"] : 0;
$this->e = array_key_exists("e",$args) ? $args["e"] : 0;
}
public function show(){
var_dump($this);
}
}
$test = new Test();
$args["c"]=999;
$test->_factory($args);
$test->show();
a full explanation can be found in my blog:
http://www.tbogard.com/2013/03/07/passing-named-arguments-to-a-function-in-php/

Related

Is it possible to make a PHP function that would take any number of arguments?

I am writing some PHP code that would generate HTML files from templates.
I would like, if possible, to make a function that would take any strings I feed the function with, and put that into the file. Like so:
function generator($a, $b, $c, $n...){
$filename = $a . ".html";
ob_start ();
echo $b;
echo $c;
echo $d;
echo $n...;
$buffer = ob_get_clean();
file_put_contents($a, $buffer);
}
I need this, because different pages would have different number of include files, and with this I would be able to skip making different functions for specific pages. Just an iterator, and that's it.
Thanks!
From PHP 5.6+ you can use ... to indicate a variable number of arguments:
function test (... $args)
{
foreach ($args as $arg) {
echo $arg;
}
}
test("testing", "variable"); // testing variable
Demo
Variable-length argument lists from the manual
So, your function would look something like this:
function generator($a, $b, $c, ... $n) {
$filename = $a . ".html";
ob_start();
echo $b;
echo $c;
foreach ($n as $var) {
echo $var;
}
$buffer = ob_get_clean();
file_put_contents($a, $buffer);
}
You can also use variadic functions (PHP 5.6+) :
function generator($a, ...$args) {
echo $a . "\n";
print_r($args);
}
generator("test", 1, 2, 3, 4);
Outputs :
"test"
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
You can make it using an array as following :
function generator($array){
// set the first item of the array as name of the .html file and take it out of the array.
$filename = array_shift($array) . ".html";
ob_start ();
// echo all the array fields
foreach($array as $a){
echo $a;
}
$buffer = ob_get_clean();
file_put_contents($a, $buffer);
}
You can pass the array directly to call the function like the following :
generator( ["val_1", "val_2", "val_3"] );
Just use func_get_args(); inside your function to return an array of all arguments passed in.
You can also use func_get_arg($arg_num) to return a specific argument, or func_num_args to return the number of arguments.
All PHP functions allow any number of parameters, they just won't be callable by name, the only way is with these 3 functions.
Note, you may use a variadic argument as the last in the parameter list like so:
function my_func($x,$y, ... $z){
//Now $z is an array of all arguments after the first two
}
In the process of good design, I would think carefully about when and where to use things such as this. For example I currently work on a project that probably has over 200K lines of code and for better of worse this is actually never used.
The most common way is to pass an array "struct" to the method:
$args = array();
$args['kitchen'] = 'sink';
$args['bath'] = 'room';
$args['cat'] = array('fur','tail');
$func->someFunction($args);
If you wanted to have more control over the data you could create a struct and access that within the class. Public functions act as handlers.
class SomeClass {
....
private $args
public function setArgs($arg1,$arg2,$arg3) {
$this->arg1 = $arg1;
...
}
public function getArgs() {
return $this->args;
}
More rarely you can have C++ like control where you use a class just as a struct:
class MyStruct {
public $foo;
public $bar;
private $secret;
private function getSecret() {
return $secret;
}
protect function setSecret($val) {
$secret = $val;
}
}
Already mentioned is '...' which I nearly never see but it's interesting, though how useful ? Does this help explain what is going on?
function someFunction(... $args)
Usually you will see a mix of things in methods which helps articulate the purpose of it.
private function someSmallFunc($list = array(), $val = '', $limit = 10)
This example is to illustrate the natural grouping of information, data is in a list, $val is used for something to control the method along with $limit say limits the number of query results. Hence, you should think in this way about your methods IMO.
Also if you notice default values are set ($limit = 10) to in case they aren't passed in. For example if you call someSmallFunc($data, $someVal) (opposed to say someSmallFunc($data, $someVal, 20) ) and not pass in $limit it will default to 10.

pass value for last default parameter of function

From very long time i am working on php.
But one question may I have no idea about
like I have one function as bellow:
function hello($param1, $param2="2", $param3="3", $param4="4")
Now whenever I will use this function and if I need 4th params thats the $param4 then still I need to call all as blank like this one:
hello(1, '', '', "param4");
So is there any another way to just pass 1st and 4th param in call rather then long list of blanks ?
Or is there any other standard way for this ?
There was an RFC for this named skipparams but it was declined.
PHP has no syntactic sugar such as hello(1, , , "param4"); nor hello(1, default, default, "param4"); (per the RFC) for skipping optional parameters when calling a function.
If this is your own function then you can choose the common jQuery style of passing options into plug-ins like this:
function hello( $param1, $more_params = [] )
{
static $default_params = [
'param2' => '2',
'param3' => '3',
'param4' => '4'
];
$more_params = array_merge( $default_params, $more_params );
}
Now you can:
hello( 1, [ 'param4'=>'not 4, muahaha!' ] );
If your function requires some advanced stuff such as type hinting then instead of array_merge() you will need to manually loop $more_params and enforce the types.
One potential way you can do this, while a little bit hacky, may work well in some situations.
Instead of passing multiple variables, pass a single array variable, and inside the function check if the specific keys exist.
function hello($param1, $variables = ["param2" => "2", "param3" => "3", "param4" => "4"]) {
if(!array_key_exists("param2", $variables)) $variables['param2'] = "2";
if(!array_key_exists("param3", $variables)) $variables['param3'] = "3";
if(!array_key_exists("param4", $variables)) $variables['param4'] = "4";
echo "<pre>".print_r($variables, true)."</pre>";
}
This will allow you to set "param4" in the above variable, while still remaining default on all of the others.
Calling the function this way:
hello("test", ["param4" => "filling in variable 4"]);
Will result in the output being:
Array
(
[param4] => filling in variable 4
[param2] => 2
[param3] => 3
)
I don't generally recommend this if it can be avoided, but if you absolutely need this functionality, this may work for you.
The key here is that you have a specifically named index inside the array being passed, that you can check against inside the function itself.
The answer, as I see it, is yes and no.
No, because there's no way to do this in a standard fashion.
Yes, because you can hack around it. This is hacky, but it works ;)
Example:
function some_call($parm1, $parm2='', $parm3='', $parm4='') { ... }
and the sauce:
function some_call_4($parm1, $parm4) {
return some_call($parm1, '', '', $parm4);
}
So if you make that call ALOT and are tired of typing it out, you can just hack around it.
Sorry, that's all I've got for you.
It is an overhead, but you can use ReflectionFunction to create a class, instance of which that can be invoked with named parameters:
final class FunctionWithNamedParams
{
private $func;
public function __construct($func)
{
$this->func = $func;
}
public function __invoke($params = [])
{
return ($this->func)(...$this->resolveParams($params));
}
private function resolveParams($params)
{
$rf = new ReflectionFunction($this->func);
return array_reduce(
$rf->getParameters(),
function ($carry, $param) use ($params) {
if (isset($params[$param->getName()])) {
$carry[] = $params[$param->getName()];
} else if ($param->isDefaultValueAvailable()) {
$carry[] = $param->getDefaultValue();
} else {
throw new BadFunctionCallException;
}
return $carry;
},
[]
);
}
}
Then you can use it like this:
function hello($param1, $param2 = "2", $param3 = "3", $param4 = "4")
{
var_dump($param1, $param2, $param3, $param4);
}
$func = new FunctionWithNamedParams('hello');
$func(['param1' => '1', 'param4' => 'foo']);
Here is the demo.

Passing an array as the parameter of a function in PHP

This is my array
$sub = array("English"=>"12","Hindi"=>"12","History"=>"12","Geography"=>"12","Mathematics"=>"12","Physics"=>"12","Chemistry"=>"12","Biology"=>"12");
Want to pass this entire array as the parameter of a function & want to sum up the marks(array values) using the function
function sum_marks($sub){--Function body--
}
I don't know if this is the proper syntax for passing an array to a function, help!!
Is this you are looking for?
$mySum = array_sum($sub);
Yes, it is the appropriate syntax for passing an array as an argument to a function.
However, you might consider adding a type declaration for the $sub argument:
function sum_marks(array $sub)
{
return array_sum($sub);
}
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
However, you really probably just want to use array_sum() directly.
For reference, see:
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
http://php.net/manual/en/function.array-sum.php
Try this. It will create a function that has a reference to your array. When you change the array you can call the product of the function, and it will recalculate the sum.
$array = ['English' => '12', 'Swedish' => '12'];
function arraySumCb(&$subject) {
return function () use (&$subject) {
return array_sum($subject);
};
}
$sum = arraySumCb($array);
echo $sum(); // 24
$array['Swedish'] = '15';
echo $sum(); // 27
$array['Swedish'] = '10';
echo $sum(); // 22
Edit: This is how I would do it.
$array = ['English' => '12', 'Swedish' => '12'];
class SumMarks {
private $_subject;
public function __construct(array &$subject = []) {
$this->_subject = &$subject;
}
public function __toString() {
return "" . array_sum($this->_subject);
}
}
$sum = new SumMarks($array);
echo $sum; // 24
$array['Swedish'] = '10';
echo $sum; // 22
Edit: Proper use of PHP anonymous functions
I dont understand your question, please ask with specific question. .
But maybe this what are you want :
function sum_marks($sub){
$result = array_sum($sub);
retrun $result;
}

Dynamically call Class with variable number of parameters in the constructor

I know that it is possible to call a function with a variable number of parameters with call_user_func_array() found here -> http://php.net/manual/en/function.call-user-func-array.php . What I want to do is nearly identical, but instead of a function, I want to call a PHP class with a variable number of parameters in it's constructor.
It would work something like the below, but I won't know the number of parameters, so I won't know how to instantiate the class.
<?php
//The class name will be pulled dynamically from another source
$myClass = '\Some\Dynamically\Generated\Class';
//The parameters will also be pulled from another source, for simplicity I
//have used two parameters. There could be 0, 1, 2, N, ... parameters
$myParameters = array ('dynamicparam1', 'dynamicparam2');
//The instantiated class needs to be called with 0, 1, 2, N, ... parameters
//not just two parameters.
$myClassInstance = new $myClass($myParameters[0], $myParameters[1]);
You can do the following using ReflectionClass
$myClass = '\Some\Dynamically\Generated\a';
$myParameters = array ('dynamicparam1', 'dynamicparam2');
$reflection = new \ReflectionClass($myClass);
$myClassInstance = $reflection->newInstanceArgs($myParameters);
PHP manual: http://www.php.net/manual/en/reflectionclass.newinstanceargs.php
Edit:
In php 5.6 you can achieve this with Argument unpacking.
$myClass = '\Some\Dynamically\Generated\a';
$myParameters = ['dynamicparam1', 'dynamicparam2'];
$myClassInstance = new $myClass(...$myParameters);
I implement this approach a lot when function args are > 2, rather then end up with an Christmas list of arguments which must be in a specific order, I simply pass in an associative array. By passing in an associative array, I can check for necessary and optional args and handle missing values as needed. Something like:
class MyClass
{
protected $requiredArg1;
protected $optionalArg1;
public function __construct(array $options = array())
{
// Check for a necessary arg
if (!isset($options['requiredArg1'])) {
throw new Exception('Missing requiredArg1');
}
// Now I can just localize
$requiredArg1 = $options['requiredArg1'];
$optionalArg1 = (isset($options['optionalArg1'])) ? $options['optionalArg1'] : null;
// Now that you have localized args, do what you want
$this->requiredArg1 = $requiredArg1;
$this->optionalArg1 = $optionalArg1;
}
}
// Example call
$class = 'MyClass';
$array = array('requiredArg1' => 'Foo!', 'optionalArg1' => 'Bar!');
$instance = new $class($array);
var_dump($instance->getRequiredArg1());
var_dump($instance->getOptionalArg1());
I highly recommend using an associative array, however it is possible to use a 0-index array. You will have to be extremely careful when constructing the array and account for indices that have meaning, otherwise you will pass in an array with offset args and wreck havoc with your function.
You can do that using func_get_args().
class my_class {
function __construct( $first = NULL ) {
$params = func_get_args();
if( is_array( $first ) )
$params = $first;
// the $params array will contain the
// arguments passed to the child function
foreach( $params as $p )
echo "Param: $p\n";
}
}
function my_function() {
$instance = new my_class( func_get_args() );
}
echo "you can still create my_class instances like normal:";
$instance = new my_class( "one", "two", "three" );
echo "\n\n\n";
echo "but also through my_function:";
my_function( "one", "two", "three" );
Basically, you simply pass the result of func_get_args to the constructor of your class, and let it decide whether it is being called with an array of arguments from that function, or whether it is being called normally.
This code outputs
you can still create my_class instances like normal:
Param: one
Param: two
Param: three
but also through my_function:
Param: one
Param: two
Param: three
Hope that helps.
I've found here
Is there a call_user_func() equivalent to create a new class instance?
the example:
function createInstance($className, array $arguments = array())
{
if(class_exists($className)) {
return call_user_func_array(array(
new ReflectionClass($className), 'newInstance'),
$arguments);
}
return false;
}
But can somebody tell me if there is an example for classes with protected constructors?

PHP Constants Containing Arrays?

This failed:
define('DEFAULT_ROLES', array('guy', 'development team'));
Apparently, constants can't hold arrays. What is the best way to get around this?
define('DEFAULT_ROLES', 'guy|development team');
//...
$default = explode('|', DEFAULT_ROLES);
This seems like unnecessary effort.
Since PHP 5.6, you can declare an array constant with const:
<?php
const DEFAULT_ROLES = array('guy', 'development team');
The short syntax works too, as you'd expect:
<?php
const DEFAULT_ROLES = ['guy', 'development team'];
If you have PHP 7, you can finally use define(), just as you had first tried:
<?php
define('DEFAULT_ROLES', array('guy', 'development team'));
PHP 5.6+ introduced const arrays - see Andrea Faulds' answer.
You can also serialize your array and then put it into the constant:
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
# use it
$my_fruits = unserialize (FRUITS);
You can store them as static variables of a class:
class Constants {
public static $array = array('guy', 'development team');
}
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';
If you don't like the idea that the array can be changed by others, a getter might help:
class Constants {
private static $array = array('guy', 'development team');
public static function getArray() {
return self::$array;
}
}
$constantArray = Constants::getArray();
EDIT
Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:
$x = Constants::getArray()['index'];
If you are using PHP 5.6 or above, use Andrea Faulds answer
I am using it like this. I hope, it will help others.
config.php
class app{
private static $options = array(
'app_id' => 'hello',
);
public static function config($key){
return self::$options[$key];
}
}
In file, where I need constants.
require('config.php');
print_r(app::config('app_id'));
This is what I use. It is similar to the example provided by soulmerge, but this way you can get the full array or just a single value in the array.
class Constants {
private static $array = array(0 => 'apple', 1 => 'orange');
public static function getArray($index = false) {
return $index !== false ? self::$array[$index] : self::$array;
}
}
Use it like this:
Constants::getArray(); // Full array
// OR
Constants::getArray(1); // Value of 1 which is 'orange'
You can store it as a JSON string in a constant. And application point of view, JSON can be useful in other cases.
define ("FRUITS", json_encode(array ("apple", "cherry", "banana")));
$fruits = json_decode (FRUITS);
var_dump($fruits);
PHP 7+
As of PHP 7, you can just use the define() function to define a constant array :
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
I know it's a bit old question, but here is my solution:
<?php
class Constant {
private $data = [];
public function define($constant, $value) {
if (!isset($this->data[$constant])) {
$this->data[$constant] = $value;
} else {
trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
}
}
public function __get($constant) {
if (isset($this->data[$constant])) {
return $this->data[$constant];
} else {
trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
return $constant;
}
}
public function __set($constant,$value) {
$this->define($constant, $value);
}
}
$const = new Constant;
I defined it because I needed to store objects and arrays in constants so I installed also runkit to php so I could make the $const variable superglobal.
You can use it as $const->define("my_constant",array("my","values")); or just $const->my_constant = array("my","values");
To get the value just simply call $const->my_constant;
Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.
<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';
echo CONSTANT;
// Works as of PHP 5.6.0
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;
const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"
// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
?>
With the reference of this link
Have a happy coding.
Can even work with Associative Arrays.. for example in a class.
class Test {
const
CAN = [
"can bark", "can meow", "can fly"
],
ANIMALS = [
self::CAN[0] => "dog",
self::CAN[1] => "cat",
self::CAN[2] => "bird"
];
static function noParameter() {
return self::ANIMALS[self::CAN[0]];
}
static function withParameter($which, $animal) {
return "who {$which}? a {$animal}.";
}
}
echo Test::noParameter() . "s " . Test::CAN[0] . ".<br>";
echo Test::withParameter(
array_keys(Test::ANIMALS)[2], Test::ANIMALS["can fly"]
);
// dogs can bark.
// who can fly? a bird.
if you're using PHP 7 & 7+, you can use fetch like this as well
define('TEAM', ['guy', 'development team']);
echo TEAM[0];
// output from system will be "guy"
Using explode and implode function we can improvise a solution :
$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1];
This will echo email.
If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :
//function to define constant
function custom_define ($const , $array) {
define($const, implode (',' , $array));
}
//function to access constant
function return_by_index ($index,$const = DEFAULT_ROLES) {
$explodedResult = explode(',' ,$const ) [$index];
if (isset ($explodedResult))
return explode(',' ,$const ) [$index] ;
}
Hope that helps . Happy coding .
Doing some sort of ser/deser or encode/decode trick seems ugly and requires you to remember what exactly you did when you are trying to use the constant. I think the class private static variable with accessor is a decent solution, but I'll do you one better. Just have a public static getter method that returns the definition of the constant array. This requires a minimum of extra code and the array definition cannot be accidentally modified.
class UserRoles {
public static function getDefaultRoles() {
return array('guy', 'development team');
}
}
initMyRoles( UserRoles::getDefaultRoles() );
If you want to really make it look like a defined constant you could give it an all caps name, but then it would be confusing to remember to add the '()' parentheses after the name.
class UserRoles {
public static function DEFAULT_ROLES() { return array('guy', 'development team'); }
}
//but, then the extra () looks weird...
initMyRoles( UserRoles::DEFAULT_ROLES() );
I suppose you could make the method global to be closer to the define() functionality you were asking for, but you really should scope the constant name anyhow and avoid globals.
You can define like this
define('GENERIC_DOMAIN',json_encode(array(
'gmail.com','gmail.co.in','yahoo.com'
)));
$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);
Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.
If you are looking this from 2009, and you don't like AbstractSingletonFactoryGenerators, here are a few other options.
Remember, arrays are "copied" when assigned, or in this case, returned, so you are practically getting the same array every time. (See copy-on-write behaviour of arrays in PHP.)
function FRUITS_ARRAY(){
return array('chicken', 'mushroom', 'dirt');
}
function FRUITS_ARRAY(){
static $array = array('chicken', 'mushroom', 'dirt');
return $array;
}
function WHAT_ANIMAL( $key ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $array[ $key ];
}
function ANIMAL( $key = null ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $key !== null ? $array[ $key ] : $array;
}

Categories