I have created function
function do_stuff($text) {
$new_text = nl2br($text);
return $new_text;
}
$result = do_stuff("Hello \n World!");
//returns "Hello <br /> World!"
I want to be able to supply another simple built in PHP function e.g. strtoupper() inside my function somehow, its not just strtoupper() that i need, i need ability to supply different functions into my do_stuff() function.
Say i want to do something like this.
$result = do_stuff("Hello \n World!", "strtolower()");
//returns "Hello <br /> World!"
How would i make this work without creating another function.
function do_stuff($text, $sub_function='') {
$new_text = nl2br($text);
$sub_function($new_text);
return $new_text;
}
$result = do_stuff("Hello \n World!");
//returns "Hello <br /> World!"
P.S. Just remembered variable variables, and googled, there's actually is Variable functions too, might answer this one myself.
http://php.net/manual/en/functions.variable-functions.php
You have it in your second example. Just make sure to check that it exists and then assign the return to the string. There is an assumption here about what the function accepts/requires as args and what it returns:
function do_stuff($text, $function='') {
$new_text = nl2br($text);
if(function_exists($function)) {
$new_text = $function($new_text);
}
return $new_text;
}
$result = do_stuff("Hello \n World!", "strtoupper");
Callables can be strings, arrays with a specific format, instances of the Closure class created using the function () {};-syntax and classes implementing __invoke directly. You can pass any of these to your function and call them using $myFunction($params) or call_user_func($myFunction, $params).
Additionally to the string examples already given in other answers you may also define a (new) function (closure). This might be especially beneficial if you only need the contained logic in one place and a core function is not suitable. You can also wrap paramters and pass additional values from the defining context that way:
Please be aware that the callable typehint requires php 5.4+
function yourFunction($text, callable $myFunction) { return $myFunction($text); }
$offset = 5;
echo yourFunction('Hello World', function($text) use($offset) {
return substr($text, $offset);
});
Output: http://3v4l.org/CFMrI
Documentation hints to read on:
http://php.net/manual/en/functions.anonymous.php
http://php.net/manual/en/language.types.callable.php
You can call a function like this:
$fcn = "strtoupper";
$fcn();
in the same way (as you found out yourself), you can have variable variables:
$a = "b";
$b = 4;
$$a; // 4
Looks like you're almost there, just need to leave off the parentheses in the second parameter:
$result = do_stuff("Hello \n World!", "strtolower");
Then this should work after a little cleanup:
function do_stuff($text, $sub_function='') {
$new_text = nl2br($text);
if ($sub_function) {
$new_text = $sub_function($new_text);
}
return $new_text;
}
I'm curious to know if there is some way to call a function using an associative array to declare the parameters.
For instance if I have this function:
function test($hello, $world) {
echo $hello . $world;
}
Is there some way to call it doing something like this?
call('test', array('hello' => 'First value', 'world' => 'Second value'));
I'm familiar with using call_user_func and call_user_func_array, but I'm looking for something more generic that I can use to call various methods when I don't know what parameters they are looking for ahead of time.
Edit:
The reason for this is to make a single interface for an API front end. I'm accepting JSON and converting that into an array. So, I'd like different methods to be called and pass the values from the JSON input into the methods.
Since I want to be able to call an assortment of different methods from this interface, I want a way to pass parameters to the functions without knowing what order they need to be in. I'm thinking using reflections will get me the results I'm looking for.
With PHP 5.4+, this works
function test($assocArr){
foreach( $assocArr as $key=>$value ){
echo $key . ' ' . $value . ' ';
}
}
test(['hello'=>'world', 'lorem'=>'ipsum']);
Check the php manual for call_user_func_array
Also, look up token operator (...). It is a way to use varargs with functions in PHP. You can declare something like this: -
function func( ...$params)
{
echo $params[0] . ',' . parama[1];
}
You can use this function internal in your functions func_get_args()
So, you can use it like this one:
function test() {
$arg_list = func_get_args();
echo $arg_list[0].' '.$arg_list[1];
}
test('hello', 'world');
The following should work ...
function test($hello, $world) {
echo $hello . $world;
}
$callback = 'test'; <-- lambdas also work here, BTW
$parameters = array('hello' => 'First value', 'world' => 'Second value');
$reflection = new ReflectionFunction($callback);
$new_parameters = array();
foreach ($reflection->getParameters() as $parameter) {
$new_parameters[] = $parameters[$parameter->name];
}
$parameters = $new_parameters;
call_user_func_array($callback, $parameters);
I can't seem to find anything of this, and was wondering if it's possible to store a function or function reference as a value for an array element. For e.g.
array("someFunc" => &x(), "anotherFunc" => $this->anotherFunc())
Thanks!
You can "reference" any function. A function reference is not a reference in the sense of "address in memory" or something. It's merely the name of the function.
<?php
$functions = array(
'regular' => 'strlen',
'class_function' => array('ClassName', 'functionName'),
'object_method' => array($object, 'methodName'),
'closure' => function($foo) {
return $foo;
},
);
// while this works
$functions['regular']();
// this doesn't
$functions['class_function']();
// to make this work across the board, you'll need either
call_user_func($functions['object_method'], $arg1, $arg2, $arg3);
// or
call_user_func_array($functions['object_method'], array($arg1, $arg2, $arg3));
PHP supports the concept of variable functions, so you can do something like this:
function foo() { echo "bar"; }
$array = array('fun' => 'foo');
$array['fun']();
Yout can check more examples in manual.
Yes, you can:
$array = array(
'func' => function($var) { return $var * 2; },
);
var_dump($array['func'](2));
This does, of course, require PHP anonymous function support, which arrived with PHP version 5.3.0. This is going to leave you with quite unreadable code though.
check out PHP's call_user_func. consider the below example.
consider two functions
function a($param)
{
return $param;
}
function b($param)
{
return $param;
}
$array = array('a' => 'first function param', 'b' => 'second function param');
now if you want to execute all the function in a sequence you can do it with a loop.
foreach($array as $functionName => $param) {
call_user_func($functioName, $param);
}
plus array can hold any data type, be it function call, nested arrays, object, string, integer etc. etc.
I'm trying to make an associative array with values that are references to functions. What is the proper way to do this? This code works, but gives me a warning.
Code
<?php
$mergeCodes = array(
'rev:(\d+)' => reverse_me,
);
$test = "This is a [[rev:1234]] test";
echo "BEFORE: $test\n";
foreach ($mergeCodes as $code => $callback) {
$code = '\[\[' . $code . '\]\]';
$test = preg_replace_callback( "/$code/", $callback, $test );
}
echo "AFTER: $test\n";
function reverse_me($input) {
return strrev($input[1]);
}
?>
Output
PHP Notice: Use of undefined constant reverse_me - assumed 'reverse_me' in /tmp/test2.php on line 4
BEFORE: This is a [[rev:1234]] test
AFTER: This is a 4321 test
As far as I know, PHP does not have such concept. You're probably confused by JavaScript.
It seems that your final purpose is to make a call to preg_replace_callback(). As the name suggests you have to feed it with a callback and that's something pretty simple. All you need is a regular variable that contains one of these:
A string with a variable name: 'foo'
An array with a class name and a method name: array('Foo', 'doBar')
An array with a class instance and a method name: array($myFoo, 'doBar')
Find further reference at https://www.php.net/manual/en/language.types.callable.php
In PHP 5.3, you can store anonymous functions (closures) in variables:
$reverse_me = function($input) {
return strrev($input[1]);
}
$mergeCodes = array(
'rev:(\d+)' => $reverse_me
);
Or you could even do this:
$mergeCodes = array(
'rev:(\d+)' => function($input) {
return strrev($input[1]);
}
);
See http://php.net/functions.anonymous for more info.
I fixed it by making the value the string 'reverse_me'. I guess $callback being a string was not very intuitive to me.
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;
}