I want to mix a variable after call a function, but not when I set the variable.
My example code:
<?php
$greeting = "hi! {$gbye}";
function greetings() {
global $greeting;
$gbye = "goodbye!";
return $greeting;
}
echo greetings();
?>
Fiddle: http://phpfiddle.org/main/code/kd5w-p7q4
I tried escaping the $ symbol: \$, but this only gives me the complete text. And replacing the escaped symbol make the same.
The $gbye variable is inside a language file, by this reason, I have to save the word ($gbye) until I call the function (to replace it as if the full string ($greeting = "hi! {$gbye}";) was inside the function). It's just an example.
So what can I do?
For language file usage, you may want to use your own meta keyword, instead of php variable syntax. This is ensure what you want to do is seperated from what PHP wants to do. This will save you from future bugs and maintenance effort. For example,
<?php
$greeting = "hi! #gbye#";
function greetings() {
global $greeting;
return str_replace("#gbye#", "goodbye!", $greeting);
}
echo greetings();
?>
Related
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
I usually run code like this just fine:
$ZANE_REGISTER_RULES='this wont print';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='this will actually print';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
But sometime (eg: if I put this inside a phpBB page) this doesn't work (the echo says "this wont print") unless I declare the variable global the first time too:
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='my rulessssssssssssssss';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='funziona';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
I'm pretty sure that the first way is the correct one and the second one just doesn't mean anything, nevertheless the second one works, the first one doesn't.
PLEASE don't waste time replying "global are bad programming" because this is not the issue at hand, neither "why would you do such a thing?" because this is obviusly an example.
There is only one reason why this might be happening: the code in the second example is being compiled in the context of a function. That's why $ZANE_REGISTER_RULES has local scope by default.
If there is no enclosing function in the source file where the code itself appears, this means that the file is being included by some other file inside a function context, for example:
var_access.php
echo "Hello ".$name."\n";
echo "Hello ".$_GLOBALS['name']."\n";
test_1.php
// Here var_access.php is included in the global context
$name = 'world';
include('var_access.php'); // Prints "Hello world" twice
test_2.php
// Here var_access.php is included in a function context
$name = 'world';
function func() {
$name = 'function world';
include('var_access.php'); // Prints "Hello world" and "Hello function world"
}
In an attempt to speed up my workflow and help the back end guys with integration (I'm a front end dev) I'm attempting to extend the file includes function by wrapping comments around each file include to output it's filename:
function include_module($path) {
echo "\n\n<!-- MODULE: ".basename($path, '.php')." -->\n";
include($path);
echo "\n<!-- /MODULE: ".basename($path, '.php')." -->\n\n";
}
include_module('form-controls.php');
However this results in the loss of access to any variables set outside the function. I know I can do:
global $var
But that will only give me access to $var (I'm aware I could do $var['var1'], etc), is there any way to do 'global all' or can anyone think of a different approach to wrap the comments?
Cheers :)
Try this:
function include_module($path) {
foreach($GLOBALS as $name => $value) global $$name;
echo "\n\n<!-- MODULE: ".basename($path, '.php')." -->\n";
include($path);
echo "\n<!-- /MODULE: ".basename($path, '.php')." -->\n\n";
}
include_module('form-controls.php');
You can use the following to access the globals.
extract($GLOBALS, EXTR_REFS);
im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get the final page. The thing is, i need some scrap of code developed by other member of the team, and i need it to be a string, but the code is available as a php file which im supposed to include or require inside my page.
Since im not writing an ht;ml page, but a function that generate that code, i need to turn the resulting html of the require statement into a string to concatenate it to the code generated by my function.
Is there any way to evaluate the require and concatenate its result to my strings?
Ive tried the function eval(), but didnt work, and read some thing about get_the_content(), but it isnt working either. I dont know if i need to import something, i think it have something to do with wordpress, and im using raw php.
thanks for all your help!!! =)
Try the ob_...() family of functions. For example:
<?php
function f(){
echo 'foo';
}
//start buffering output. now output will be sent to an internal buffer instead of to the browser.
ob_start();
//call a function that echos some stuff
f();
//save the current buffer contents to a variable
$foo = ob_get_clean();
echo 'bar';
echo $foo;
//result: barfoo
?>
If you want to put the echo'd result of an include into a variable, you could do something like this:
//untested
function get_include($file){
ob_start();
include($file);
return ob_get_clean();
}
or if you want to put the echo'd result of a function call into a variable, you could do something like this:
//untested
//signature: get_from_function(callback $function, [mixed $param1, [mixed $param2, ... ]])
function get_from_function($function){
$args = func_get_args();
shift($args);
ob_start();
call_user_func_array($function,$args);
return ob_get_clean();
}
Depending on how the other file works...
If the other file can be changed to return a value, then you should use:
$content = require 'otherfile';
If the other file simply uses echo or some other way to print directly, use:
ob_start();
require 'otherfile';
$content = ob_get_clean();
You can receive string with include or require but you have to update those files before including to add return statement.
the file to be included should return result like this
<?php
$var = 'PHP';
return $var;
?>
and you can receive the $var data by including that file
$foo = include 'file.php';
echo $foo; // will print PHP
Documentation section
I am trying to insert messages to a function
function addMessage($item) {
if ($result) {
$message = '<p class="ok">
<span> Item added </span>
</p>
';
header("Refresh: 2; url=?page=$item");
}
else{
$message = '<p class=not><span>There is an error blah blah</span></p>';
}
return $message;
}
When I use it : addMessage('contents') it only returns to second condition. How can I fix this?
You are checking $result inside the if but its neither been assigned any value before that nor been declared as global . I think you meant to check $item:
if ($item) {
Hi jasmine
Your function always returns the second condition because you haven't assigned a value to $result, eider inside the function or when you call the function (like unicornaddict mentioned by other words).
To get your code working the way you probably want, your function should be like this:
function addMessage($item, $result) {
if ($result) { // It will return this condition, case $result has any value assigned and is different from FALSE (boolean)
$message = '<p class="ok">
<span> Item added </span>
</p>
';
header("Refresh: 2; url=?page=$item");
}
else{ // It will return this condition, case $result doesn't has any value assigned or is equal to FALSE (boolean)
$message = '<p class="not"><span>There is an error blah blah</span></p>';
}
return $message;
}
And then you can call the function like you where already calling it, but don't forget to include a variable or a value that should be handled as the $result variable inside the function
addMessage('contents', $result);
Note:
In your $message variable you have <p class=not> and should be <p class="not">.
Remember that header() must be called before any actual output is sent to the browser.
Hope it Helps.
Is $result defined in your script? Use if ($item) instead.
Be very careful that PHP allows the usage of undefined variables.
what they said :-)
Btw, a decent IDE (like Zend) will analyze your code and warn you about things like that.
Such static code analysis is known as "linting", so google for "PHP lint" or see questions like Is there a static code analyzer [like Lint] for PHP files?
But this code sample is so small that I guess you are a beginner (no offence interned - we all had to start somewhere), so do a lot of reading and gather a lot of tools and experience.
For instance, a decent IDE (like Zend or Eclipse PDT) would let you step through your code, line nby line, and examine the value of each variable and then you ought to have seen the problem.
Welcome to PHP and good luck!