can someone pls fill me in on the correct syntax for this in PHP? I have:
function mainFunction($str,$thingToDoInMain){
$thingToDoInMain($str);
}
function printStr($str){
echo $str;
}
mainFunction("Hello",printStr);
I am running this on WAMP and I get an error/warning saying
use of undefined constant printStr - assumed 'printStr' on line 5
...and then I get "Hello" printed out as desired further down the page.
So, how do a refer to the function printStr in the last line to get rid of warning? I have tried $printStr, printStr() and $printStr. Thanks in advance.
Simply add a $ sign before your thingToDoInMain function call making it a proper function name, because thingToDoInMain itself is not a function name. Whereas the value contained in $thingToDoInMain is a function name.
<?php
function mainFunction($str,$thingToDoInMain){
$thingToDoInMain($str); //Here $ is missing
}
function printStr($str){
echo $str;
}
mainFunction("Hello","printStr"); // And these quotes
?>
Demo
In PHP, function names are passed as strings.
mainFunction("Hello", "printStr");
Related
I have a PHP class where one of the private member is a callback to my log function (i.e. in PHP land, a function pointer is simply a string containing the name of the function to call).
self::$logferr = "msgfunc";
self::$logferr($res);
I get this error:
Fatal error: Function name must be a string
self::$logferr is equal to "msgfunc" which is my log function.
If I rewrite the code like this (on the same very class method):
$tmp = "msgfunc";
$tmp($res);
It works, the log function get called
Just wrap your variable in parenthesis, let PHP resolve the value first:
(self::$logferr)($res);
Proof of concept
You can use call_user_func. ref: this
call_user_func(self::$logferr, $res);
You should call it by using
self::{self::$logferr}($req)
Working example : https://3v4l.org/CYURS
Let's build a reproducible example:
class Foo {
private static $_loggerCallback;
static function setLogCallback(callable $loggerCallback) {
self::$_loggerCallback = $loggerCallback;
}
static function log(...$arguments) {
if (NULL !== self::$_loggerCallback) {
return self::$_loggerCallback(...$arguments);
}
return NULL;
}
}
Foo::setLogCallback(function() { echo 'success'; } );
Foo::log();
Output:
Notice: Undefined variable: _loggerCallback in /in/f3stL on line 13
Fatal error: Uncaught Error: Function name must be a string in /in/f3stL:13
The notice reports the actual mistake in this case. If you do not get something like it, you should check your error reporting configuration.
The notice shows that PHP looks for a local variable $_loggerCallback. It tries to execute $_loggerCallback(...$arguments). Here are different possibilities to make the call explicit.
Use parenthesis (PHP >= 7.0):
return (self::$_loggerCallback)(...$arguments);
Use a local variable (as you did):
$callback = self::$_loggerCallback;
return $callback(...$arguments);
A small advise. PHP support anonymous functions. You do not need a (global) function for a callback. This avoids calling to the function by name as well.
I tried substr() method in PHP 5.6 to get some part of String,
first,
<?php
echo substr("Avicienna", 0,3);
and save it to a file.
second one,
<?php
class Test{
public function index(){
$name = "Hasan";
var_dump(subtr($name,0,3));
}
}
$test = new Test();
$test->index();
and save it to another file.
the first one without class, return correct string parts, while, the second one return PHP 500 error :
Call to undefined method Coba::subtr() in /var/www/html/koper/coba.php on line 5
is there any limitation to call substr() or others php function inside a class ?
Typo error subtr() . Its substr().
I have this code:
return t("Use tokens like: eg. [youtube_video:id]");
Because of the brackets used in my string PHP treat this [youtube_video:id] as an array key and returns notice like: Notice: Use of undefined constant _miscellaneous_filter_tips - assumed '_miscellaneous_filter_tips' w miscellaneous_filter_info_alter()
How can I resolve it?
All the code after a request:
function _miscellaneous_filter_tips() {
return t('Use tokens like: eg. [yamandi:youtube_video:id]');
}
function miscellaneous_filter_info_alter(&$info) {
$info['filter_tokens']['tips callback'] = _miscellaneous_filter_tips;
}
since I don't have the precursor code I can't actually see what the function t() does, however if is seems to think you are calling a variable try using
return t('Use tokens like: eg. [youtube_video:id]');
or if you still want to use variables
return t("Use tokens like: eg. " . '[youtube_video:id]');
Just change the double quote into a single quote:
return t('Use tokens like: eg. [youtube_video:id]');
EDIT
After looking to the updated code, this might be a completely different issue, I think you might wanna try this way of storing function hooks:
function _miscellaneous_filter_tips() {
return t('Use tokens like: eg. [yamandi:youtube_video:id]');
}
function miscellaneous_filter_info_alter(&$info) {
$info['filter_tokens']['tips callback'] = '_miscellaneous_filter_tips';
}
And then when you want to call that function, you can simply use:
$info['filter_tokens']['tips callback']();
<?php
function dosomething(){
echo "do\n";
}
$temp="test".dosomething();
echo $temp;
?>
expected result:testdo
but actual result is:
do
test%
I know how to change the code to get the expected result.
But what i doubt is why the code prints result like this.
Can someone explain it?Thanks!
dosomething is echoing to the screen. Since this runs first "do\n" is printed.
dosomething also doesn't return anything so the second echo is equivalent to echo "test";
In order to use the result of the call you should return it:
function dosomething(){
return "do\n";
}
Which will behave as you expect.
To clarify. In order to work out what $temp is the function must be run first which prints out "do\n" first.
Use return.
function dosomething(){
return "do\n"; }
Use a return statement instead of echo
function dosomething(){
return "do\n";
}
I'm not sure why people are getting down voted. Their answers are right.
http://codepad.org/nagGXY99
Try this:
Use return in the calling function. Doing that you will get the string where the function is being called. So function is being replaced by string and 2 strings will then con cat.
-
Thanks
can I use a function that is outside the current function?
eg.
function one($test){
return 1;
}
function two($id){
one($id);
}
Seems like i cant, how should I do it then to use the function that are outside? Thanks
The function is in the same file.. /
Is your function inside of a class? In that case you have to use $this->function() instead of function().
That's perfectly valid. Check out the running code here.
Your code looks valid to me : you are declaring two functions, called one and two ; and two is calling one.
Then, you can call any of those functions, to execute it.
For example, if you execute the following portion of code :
function one($test){
var_dump(__FUNCTION__);
return 1;
}
function two($id){
var_dump(__FUNCTION__);
one($id);
}
two('plop');
Note that I called two, in the last line of this example.
You'll get this kind of output :
string 'two' (length=3)
string 'one' (length=3)
Which shows that both functions were executed.
That works fine. However, one ignores its parameter. Then, two ignores the return value from one.
This should work fine
Example:
<?php
function test ($asd)
{
return $asd;
}
function run ()
{
return test('dd');
}
echo run();
?>
Maybe you have an issue elsewhere?