In PHP I can say
$noun = "bird";
$adjective = "warm;
echo <<<EOT
The $noun is very $adjective
EOT;
and it will output
The bird is very warm
Is there a way to do this with functions?
function getNoun() { return "bird"; }
function getAdjective() { return "warm"; }
echo <<<EOT
The getNoun() is very getAdjective()
EOT;
and output
The bird is very warm
You can use variable functions, though they're rather frowned on upon as they're not far different from variable variables...
$a = 'getNoun';
$b = 'getAdjective';
echo <<<EOT
The {$a()} is very {$b()}
EOT;
You could store it in a variable before using it:
$noun = getNoun( );
$adj = getAdjective( );
echo <<<EOT
The {$noun} is very {$adj}
EOT;
echo "The ";
echo getNoun();
echo " is very ";
echo getVerb();
Or maybe even (not 100% sure):
echo "The " . getNoun() . " is very " . getVerb();
Here is a solution using variable functions, although not exactly:
$noun=function($type){
return $type;
};
$adjective=function($adj){
return $adj;
};
echo "{$noun("Robin")} was very {$adjective("Warm")}";
Related
I have multiple variables:
$Variable1 = '5/5/15';
$Variable2 = '6/13/76';
$Variable3 = '5/8/15';
...
I have an iteration variable:
$Iteration1 = 1;
while($Iteration1<=3){
echo "$Variable" . $Iteration1;
$Iteration1++;
}
desired result:
5/5/15
6/13/76
5/8/15
The Problem
Your current code echo "$Variable" . $Iteration1; tries to echo the value of the variable $Variable, which doesn't exist, and concatenate $Iteration1.
The Solution
What you want to do is build a string, "Variable" . $Iteration1 (e.g., $Variable2), then get the value of the variable with that name. This is called a "variable variable." You do this by writing ${string_you_want_to_create}, as in ${"Variable" . $Iteration1}.
Example Code For your Problem:
$Variable1 = '5/5/15';
$Variable2 = '6/13/76';
$Variable3 = '5/8/15';
$Iteration1 = 1;
while ($Iteration1 <= 3) {
echo ${"Variable" . $Iteration1} . "\n";
$Iteration1++;
}
Output:
5/5/15
6/13/76
5/8/15
Note: You could also do this in two steps, like this:
$variableName = "Variable" . $Iteration1;
echo $$variableName; // note the double $$
Try like this
echo ${"Variable" . $Iteration1};
Try this in loop
$var = 'Variable'.$Iteration1;
echo $$var.'<br>';
$count = 2;
$amt = 4;
$str = function($count, $amt) {
return "There is ". $count . " and " . $amt;
};
echo $str . "!";
How do I store the return value from the anonymous function into a variable? I know that the entire function itself is being stored into $str which is why this doesn't work, but is there a way to?
You should simply call $str as a function:
echo $str() . "!"
Documentation for anonymous functions as php.net: http://www.php.net/manual/en/functions.anonymous.php
So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.
1) in the view I could echo out my variables in like my footer (yuuuck!)
2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?)
3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.
What's the best maintainable way to implement PHP into JS in a MVC framework?
To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...
$variables_to_view['js_variables']['var_name'] = $var_name;
then pass it to the view
php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);
There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.
You can use short tag like this:
For Example:
You want to use $abc variable in js, then you will need to write this in js
var abc = <?=$abc?>;
You can create php file .
Something like script.js.php?outfor=1;
<?php
header("Content-type:text/javascript"); //can be application/javascript.
?>
ABC = <?php echo $abc?>
CBA = <?php echo $cba?>
BAC = <?php echo $bac?> //and so on.
Some additional info .
If you use "var" in function that variable will be visible only in that function and without "var"means global.
So.
function abc()
{
var a = 1; //only in abc()
b=2; //global
}
I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help.
The xml is the simplest possible; value
<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "******** GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo " input xml file: ". GECOXML_PATH."<br>";
echo " output php file: ". PHP_GECO_FN."<br>";
echo " output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";
$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP = gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);
//****** Functions *********
function xmlParse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
return simplexml_load_string($fileContents);
}
function writeFiles($PHPcontent, $JScontent)
{
echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent) . "<br>";
echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}
function gecoPHP($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "define(\"" . $key . "\",". intval($value) . ");\n";
}
else
{
$line = "define(\"" . $key . "\",\"". $value . "\");\n";
}
$phpContent = $phpContent . $line;
echo $line."<br>";
}
return "<?php\n"$phpContent."?>";
}
function gecoJS($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "var " . $key . "=". $value . ";\n";
}
else
{
$line = "var " . $key . "=\"". $value . "\";\n";
}
$JSContent = $JSContent . $line;
echo $line."<br>";
}
return $JSContent;
}
?>
$s = $testObj->str;
// hypothetical
echo $s
// works
however
$out = "foo" . $s . "bar;
echo $out;
doesn't
tried () typecasting and strval, can't really think of anything else to do
You have a typo in 2nd string. Should be:
$out = "foo" . $s . "bar";
echo $out;
actually you can do
$str = "foo{$testObj->str}bar";
echo $str;
here .. a testcase : http://codepad.viper-7.com/8PCCkK
{$thisname} should be converted to <?php echo $thisname; ?>.
{thisname} should be converted to <?php echo $thisname; ?>.
{$this.movie.games} && {$this.new} should be converted respectively to <?php echo $this["movie"]["games"]; ?> and <?php echo $this["new"]; ?>.
$tpl = 'Name: {$name}, Surname: {surname}, City: {$person.address.city}';
function tpl2php($m){
$var = $m[1];
if(strpos($var,'.')){
$varArr = explode('.',$var);
$var = $varArr[0];
for($i=1;$i<count($varArr);$i++){
$var .= '["' . $varArr[$i] .'"]';
}
}
return '<?php echo $' . $var . '; ?>';
}
$php = preg_replace_callback('/{\$?([_a-z][\w\.]+[\w])}/iS','tpl2php',$tpl);
// Name: <?php echo $name; ?>, Surname: <?php echo $surname; ?>, City: <?php echo $person["address"]["city"]; ?>
Use a templating system, I suggest using http://phpsavant.com/ although it looks like you're more interested in Smarty or Dwoo
There's no need to re-invent the wheel :)
Use the str_replace function.
preg_replace and regular expressions are more flexible than str_replace, especially if you have to parse a string like this.movie to $this["movie"]. It will not be an easy task though.