How to echo an function - php

I've been struggling to echo the output of a function. I tried this:
echo 'myFunction('foo')';
.. which obviously won't work, due to the extra single quotes. Any suggestions?

Let's take this function :
function getStr()
{
return "hello";
}
It will simply return a string, which means, calling this :
echo getStr();
Has the same exact result as calling this :
echo "hello";
Which means, the result of your function can be treated just like a variable (except you cant modify it), so you can do whatever you want with the result :
$string = getStr() . ' - ' . getStr();
echo $string; // Will print "hello - hello";

After trying a little while, I tried calling echo as an function:
echo (myFunction('foo'));
This works perfectly. I couldn't find this elsewhere on the internet (maybe I'm just a bad googler). Anyways, I thought I could might share this with you guys. In case anyone ever runs into the same problem.

Try this:
echo myFunction('foo');

Related

Inserting variable in echo function

I have have some php code that I can't get to work ...
I can't seem to find my mistake :/, I realize it's going to be a syntax error but after looking for an hour with no success I turn to you guys for help =)
Here is the code:
<?php
$t= number_latest_added();
for ($n = 0; $n<$t; $n += 3) {
$latest = latest($n);
echo "<a class=\"example-image-link\" href=\"" .$latest. "\" data-lightbox=\"example-set\" data-title=\"De la galerie : " . $latest . "\"><div id=\"a\" style=\"background: url(" . $latest . ") 50% 50% / cover;background-size: contain;background-repeat: no-repeat;\"></div></a></br>";
}
?>
The problem is in getting the echo to concatenate with the variable but it isn't working ( the variable is echoed 3 times and then the text is echoed with blank instead of the variable) and I don't understand why not ...
If somebody could help me see my error; it would be great!
What is the function latest? From what you are saying I am guessing it is something like:
function latest($number) {
echo $number;
}
and you need something like:
function latest($number) {
return $number;
}
Make sure you turn on error reporting ini_set('display_errors', 'On');
In addition to that, php automatically parses variables to string, if your inside double quotes.
Example:
$var = "hello"
echo "$var world" //prints hello world
Your problem is that latest($n) doesn't return anything printable, you can find that out by simply echo'ing the value itself.

Closure within a string in PHP

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

Modified variable variables

$m = 'this_is_m';
$this_is_m = 'this_is_m_not_full :(';
$this_is_m_full = 'this_is_m_FULL!! :D';
print ${$m};
(Hi first :P) Outputs:
this_is_m_not full :(
Any idea how to output this_is_m_FULL!! :D using $m??
What I've already tried:
print $"{$m}_full";
print $'{$m}_full';
print $'$m_full';
print ${$m}_full';
None worked... Thanks in advance,,
The solution would be:
print ${$m . '_full'};
But that feels very hackish.
To get your desired output, you need to do the following:
print ${$m . "_full"};
The following should work:
print ${$m.'_full'};
This is because the string inside the braces will get evaluated first, becoming
print ${'this_is_m' . '_full'}
-> print ${'this_is_m_full'}
-> print $this_is_m_full
Take a look at this manual page if you want more information on this.

identify and execute php code on a string

I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.

echo function output inside html

I have something like this in one field of my table(MySql):
$data = '<td>apple</td>';
echo $data;
I select this field and echo it into the page.I want to replace 'apple' word with a php function that return a word.So I thought
$data = '<td>myphp_function('fruit');</td>';
echo $data;
but what I see in the page is exactly the line above and not my function output.
how can I do it?
I am not sure if i could explain my mean clearly...
Edited.
According to your last edit, what you need is the following:
$data = '<td>' . myphp_function('fruit') . '</td>';
echo $data;
This is assuming your myphp_function() will return some kind of value.
If the function echoes the value, it will not work as expected!
You can only execute PHP when you open PHP tags. Other than that, it's just plain text/html.
<td>myphp_function('fruit');</td>
To execute your function you have to open PHP tags:
<td><?php myphp_function('fruit'); ?></td>
you have to insert some sort of placeholder into your text. Like this
<td>[fruit]</td>
and then do a replace before printing it out:
$fruit = 'apple';
$text = str_replace('[fruit]',$fruit,$text);
Of course, for the real life usage there will be more complex solution.
So, you will do yourself enormous favor, if you post here your real task with real data example, not oversimplified and useless abstract question.

Categories