I want to create and execute a closure within a string in PHP and it's not liking the way that I do it.
This code doesn't work...
echo ( 'Hello, ' . (function($s) { return $s; })('World!') );
Yet, this is completely valid and works as intended...
$f = (function($s) { return $s; });
echo ( 'Hello, ' . $f('World!') );
Why won't the first one work and is there a way to do it in one line (not because I think it's efficient, because I'm sure it's not)?
You may want to take a look at Self Executing functions in PHP5.3?.
Essentially, no self-invoking with "(...)()" until (maybe) sometime in 5.4.
https://wiki.php.net/rfc/fcallfcall
I believe that's only possible in PHP 5.4: http://php.net/manual/en/migration54.new-features.php
Related
i need to create function in word press function file to print some HTML cord. i tried this function.
function pre($chord){
echo '<pre>$chord</pre>'
}
and i use it in my post like this
<?php pre("sd");?>
and it will not work. please help me.
You are building your string incorrectly. when mixing html and php strings you need to concatenate the data like so...
function pre( $chord ) {
echo '<pre>' . $chord . '</pre>';
}
Also bear in mind that Wordpress is a large and modular CMS so by naming your function something as simple as pre you run the risk of conflicting with some other function called pre. It's good practise to prefix your functions with a unique string of letters like so...
function abc_pre( $chord ) {
echo '<pre>' . $chord . '</pre>';
}
Use whatever works for you.
Dan
In Drupal, there are many functions that are hook_functionname1, hook_functionname2. When writing a module, you have to replace the text 'hook' with your module name, so Drupal loads your module "my_drupal_module" and runs hooks like "my_drupal_module_functionname1" and "my_drupal_module_functionname2".
Is it possible in PHP to use DEFINE to simply define the word "hook" and set it to a string? If it is possible, then you should be able to copy and paste word-for-word hook_anything and not have to change it. And, if you ever wanted to change the name of your module, you would merely change the single constant, rather than find/replace all the function names.
So can you use DEFINE or some other setting to meta-program in PHP?
You want something like:
$moduleFunctionName = 'hook';
$functionNameOne = $moduleFunctionName . '_functionname1';
$functionNameTwo = $moduleFunctionName . '_functionname2';
$functionNameOne = function($var) {
// blah
}
..//
Function $functionNameOne is defined through anonymous function. It becames available in php from php 5.3.0
Maybe you want something like this
<?
define('PREFIX', 'myprefix');
//like this time you deside that this will me the second part
$somevar = '_this_function_name';
// now we combine prefix and name
$function_name = PREFIX . $somevar;
// now we check if we can run this function
if(!function_exists($function_name)){
echo "no function $funcion_name exist";
}
else{
$function_name();
}
function myprefix_this_function_name(){
echo 'running function';
}
?>
this will output
running function
This actually works:
define('FN_NAMESPACE', 'hook_');
${FN_NAMESPACE . 'functionNameOne'} = function($var) {
echo "Hi, I got $var\n";
};
$hook_functionNameOne('test');
Will output
Hi, I got test
When I use an anonymous function ( but see also note below ) like :
$f = function() use ($out) {
echo $out;
};
It produces an parse error on servers where PHP is older than 5.3.0.
My software needs to be compatible with unknown servers , but in the same time , I want also to use new functions, so I thought I will add some kind of a version check,
if (o99_php_good() != true){
$f = function() use ($out) {
echo $out;
};
}
where the o99_php_good() is simply
function o99_php_good(){
// $ver= ( strnatcmp( phpversion(),'5.3.0' ) >= 0 )? true:false;
$ver= ( version_compare(PHP_VERSION, '5.3.0') >= 0 )? true:false;
return $ver;
}
But still the error is produced .
Is there a way to somehow "isolate" that part of the code ?
I thought of doing a conditional include() based on a version check , which would probably work, but it will be absurd to make a separate file every time I need to use a function...
Any creative ( or trivial ) solution for that ?
Note : the example here is just a Lambda function, but the problem can occur in every other function which is a new feature and/or might not be supported on some servers ..
Edit I after comment .
Adding a "minimum requirements" list is always good, but it does not resolve the problem.
If one does not want to loose users (not all customers are happy or can upgrade their servers every time I will update a new function ) it will just force me to "fork" my software into 2 (or possibly more ) unmanageable versions..
I had exactly the same problem and solved it using eval function :
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
eval('
function osort(&$array, $prop)
{
usort($array, function($a, $b) use ($prop) {
return $a->$prop > $b->$prop ? 1 : -1;
});
}
');
} else {
// something else...
}
The only thing I can think of is to make a build script which people will have to run to make it compatible with lower versions.
So in case of anonymous methods, the script will loop through all the PHP files, looking for anonymous methods:
$f = function($a) use($out) {
echo $a . $out;
};
and replace them with create_function for < 5.3:
$f = create_function('$a', '
global $out;
echo $a . $out;
');
Anonymous functions came with PHP 5.3.0.
My first thing to do would be to replace with one of the following:
$my_print_r = "my_print_r";
$my_print_r();
or
$my_print_r = create_function('$a','print_r($a);');
UPDATE:
i would go with the first method... It would give me enough control for creating my own function versions and in much easier procedure than create_function, regardless of PHP version. I never had any problems with that approach. In fact i once built a whole multidimensional array of functions, that was easily manageable and able to add/remove functions, think of that.. That system was also used by other users, they were able to add their functions too in a way.
use include
if (o99_php_good() != true){
include 'new_func.php';
}
new_func.php:
$f = function() use ($out) {
echo $out;
};
I am trying to grasp the concept of PHP functions. I know how to create one.
function functionName()
{
//code to be executed;
}
I also know how to call a function. I am just a little confused as to what a parameter is for. I have read the php manual and w3schools.com's tutorial. From my understanding, you need a parameter to pass a value to the function? If that is correct why not just create it within the function? Why use a parameter?
Like this:
<?php
function num()
{
$s=14;
echo $s;
}
num();
?>
I know you can do:
<?php
function num($s=14)
{
echo $s;
}
num();
?>
or:
<?php
function num($s)
{
echo $s;
}
num($s=14);
?>
Could someone give me a real application of using a parameter, for say maybe a user based dynamic content website? I think it would help me understand it better.
Passing a parameter allows you to use one function numerous times. For example:
If you wanted to write ONE function that sent mail - you could pass the following parameters:
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
Then, in your function:
function sendmail($to, $from, $subject){
//code to be executed
}
Now you can reuse your send function at various points in your web app.
Here is an example, say you have numbers representing colors (this is common in storing data in a database) and you want to output what number represent's what color.
Say you had to do this a hundrend times for a hundred numbers.
You'd get pretty tired writing 100 if statments 100 times.
Here is a function example...
function colorType($type) {
if ($type == 1) {
return "Green";
}
elseif ($type == 2) {
return "Blue";
}
elseif ($type == 3) {
return "Red";
}
// etc
}
echo colorType(1) . "<br>"; // Green
echo colorType(2) . "<br>"; // Blue
echo colorType(3) . "<br>"; // Red
A function does something, and gives a result. It may accept parameters to arrive at that result, it may not. The simple calculator, as aforementioned, is a good one.
The easiest way to understand functions and parameters is to just read the PHP manual—most of the functions in the core PHP language take parameters of some sort. These functions are no different to the functions you write.
Let's assume you want to create a function that will allow people to sum numbers, you can't write needed variables in functions because you want others to input it and your function shows output:
function add($num1, $num2){
return $num1 + $num2;
}
Now anyone can call/use your function to sum numbers:
echo add(5,1); // 6
echo add(2,1); // 3
echo add(15,1); // 16
That's the most simplest example one can give to explain why you need parameters :)
When you specify function name($var=VALUE), you are setting a default.
function doit($s=14) {
return $s + 5;
}
doit(); // returns 19
doit(3); // returns 8
it makes your functions flexible to be reused in various situations, otherwise you would have to write many functions, one for each scenario. this is not only tedious, but becomes a nightmare if you have to fix something in those functions. instead of fixing it in one place, you would have to fix it in many places. you basically never want to have to copy paste code you have already written, instead you use arguments to make one set of the code flexible enough to handle each situation.
Paramaters allow your function to see the value of variables that exist outside of itself.
For example:
function F_to_C($temp) {
$temp = ($temp - 32) / 1.8;
return $temp;
}
$temperature = 32;
$new_temperature = F_to_C($temperature); // 0
echo $temperature;
$temperature2 = F_to_C(212); // 100
echo $temperature2;
Here we take $temperature, which we define in the code, but could be user input as from a form, and then send it to the function F_to_C. This allows us to convert it to Celsius, so we can then display it thereafter. In the next section, we then re-use the function to convert the boiling point, which is sent directly this time as the value 212. If we had embedded $temperature = 32 in the function the first time, then we would still get 0 as a result. However since we're using parameters, we instead get 100 back, because it's processing the value we specified when we invoked the function.
function mainFunction() {
functionA(5, "blah");
functionB("ok", "whatever");
}
How to write a function GetFunctions that returns the functions within mainFunction?
How to call them with the parameters given in mainFunction?
How to call them as follows?
foreach (GetFunctions(mainFunction) as $function) {
print "Calling function $function: ";
call($functionA); // called with parameters(5, "blah")
}
Working in PHP 5.2.8
EDIT: OK, here's a more complete explanation. I tried to keep it simple to make it easy to understand, but apparently that wasn't a good idea.
The goal is to call each assertion within a given static method. I am writing a testing framework. Each assertion returns true or false.
I am calling the methods as follows.
$methods = get_class_methods('LibraryTests');
foreach ($methods as $method) {
if ( StartsWith($method, 'Test') ) {
print "calling: " . $method . ": ";
call_user_func('LibraryTests::' . $method);
}
}
The above code calls each method within the class, but I want to call each assertion individually and track the result (true/false). CallAssertion is supposed to call each assertion (such as TestUnit::AssertEqual(GetFormattedHour(5), "5 PM");). This is the method that I am asking about.
Here is the class:
class LibraryTests extends TestUnit {
static $success = 0;
static $failure = 0;
static $total = 0;
static function CallAssertion($assertion) {
self::$total += 1;
if ($assertion) { self::$success += 1; }
else { self::$failure += 1; }
}
static function TestGetFormattedHour() {
TestUnit::AssertEqual(GetFormattedHour(5), "5 PM");
TestUnit::AssertEqual(GetFormattedHour(16), "4 PM");
}
So, the question is, how to write CallAssertion?
You can't.
Instead, create a class and use reflection to get its methods.
Regardless, you'll want to figure out why this is necessary and see if there is an entirely different approach you can use.
(If this is for debugging purposes, you can use debug_backtrace to inspect but its purpose is not for calling functions as you have described in your question.)
Hmm, what problem are you actually trying to solve. To me it sounds like you're trying to inspect the call stack at runtime. If so, I'd suggest just using debug_backtrace() (src).
I wouldn't suggest using that function in production as much though, as it's a rather heavy hit on your code.
One possibility would be to do a file_get_contents on the PHP file that contains main_function, then go through it to parse out main_function and the functions it calls. Of course, I don't know your situation so that might not work.
You can do this with:
http://php.net/manual/en/function.token-get-all.php
Probably a bad idea, but good luck!