create local variable in calling function, from a string - php

I want to be able to call a function, that will set one or more local variables in the calling function. For instance:
function someFunc () {
loadTranslatedStrings($LOCALS, "spanish");
echo $hello; // prints "hola";
}
function loadTranslatedStrings (&$callerLocals, $lang) {
if ($lang == 'spanish')
$callerLocals['hello'] = 'hola';
else if ($lang == 'french')
$callerLocals['hello'] = 'bonjour';
else
$callerLocals['hello'] = 'hello';
}
(I'm guessing it is impossible to do this, but might as well ask...)

You could do this...
function someFunc () {
loadTranslatedStrings($lang, "spanish");
extract($lang);
echo $hello; // prints "hola";
}
CodePad.

The closest I think you could get is by using extract:
function someFunc()
{
extract(loadStrings('french'));
echo $hello;
}
function loadStrings($lang)
{
switch($lang)
{
case 'spanish':
return array('hello' => 'hola');
case 'french':
return array('hello' => 'bonjour');
}
}

You can do that using $GLOBALS: $GLOBALS['hello'] = 'hola';

Related

Calling a function with a variable variable

I'm trying to call a function with a php variable variable. You'll see in my code in function mainFunction(). If it's not possible to do it this way, is there a better way to do it, that avoids any more code? I wish it would work this way.
<?php
$a = 1;
$b = 1;
if ( $a == $b ) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction();
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$$exampleFunction();//Here's where I'm stuck.
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
?>
A way to solve this problem would be to use PHP's call_user_func function. Here is the modified code (it also removes the global variable):
Code Example
<?php
$a = 1;
$b = 1;
// I'm just using this to hold the function name,
// to get rid of the global keyword. It will be passed
// as an argument to our mainFunction()
$exampleFunction = '';
if ($a == $b) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction($exampleFunction);
function mainFunction($func) {
echo 'This is mainFunction <br>';
// Use PHP's call_user_func. We are also checking to make sure
// the function exists here.
if (function_exists($func)) {
// This will call the function.
call_user_func($func);
}
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
Output
When I run this code, it produces the following output:
This is mainFunction
This is example two
Try like
if ( $a == $b ) {
$exampleFunction = exampleOne();
} else {
$exampleFunction = exampleTwo();
}
and your functions should return like
function exampleOne() {
return 'This is example one <br>';
}
function exampleTwo() {
return 'This is example two <br>';
}
OR if you want to call them through the variable try to replace like
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Try with $exampleFunction(); instead of $$exampleFunction();
OR
use call_user_func($exampleFunction)
check this way :-
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Use just $exampleFunction, without $$:
<?php
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
?>
See manual of variable functions, not variable variables.
P.S.: Also, I suggest $exampleFunction to be an argument of mailFunction, rather than use globals.

PHP function in a function

I am trying to build a function that will call another function.
For example, if I have an array full of function names to call, is it possible to call a function for every array value without writing it in a script?
Example:
function email($val=NULL) {
if($val)
$this->_email = $val;
else
return $this->_email;
}
function fname($val=NULL) {
if($val)
$this->_fname = $val;
else
return $this->_fname;
}
For email, fname, etc.
But I want to have it like:
function contr_val($key,$val) {
function $key($val=NULL) {
if($val)
$this->_$key = $val;
else
return $this->_$key;
}
function $key($val="hallo");
}
And call it with:
contr_val("email", "test")
You're really trying to create member variables dynamically and retrieve their values. This is what __get() and __set() are for.
Here's how you could use it:
class TestClass {
var $data = array();
public function __set($n, $v) { $this->data[$n] = $v; }
public function __get($n) {
return (isset($this->data[$n]) ? $this->data[$n] : null);
}
public function contr_val($k, $v = NULL) {
if ($v)
$this->$k = $v;
else
return $this->$k;
}
};
$sherp = new TestClass;
$sherp->contr_val("Herp", "Derp");
echo "Herp is: " . $sherp->contr_val("Herp") . "\n";
echo "Narp is: " . $sherp->contr_val("Narp") . "\n";
Something like this:
/*
Input: $val - any value
$varname - the variable name, for instance: _email
*/
function checkValue($val=NULL, $varname) {
if($val)
$this->$var = $val;
else
return $this->$var;
}
checkValue("hello", "_email");
checkValue("hello2", "_name");
If you are doing this for a class, consider using PHP's magic methods __get() and
__set().
In an array full of function names, this calls every function that exists.
ghoti#pc:~$ cat functest.php
#!/usr/local/bin/php
<?php
function one() { print "one\n"; }
function two() { print "two\n"; }
function three() { print "three\n"; }
$a=array( "one", "two", "three", "four" );
foreach ($a as $item) {
if (function_exists($item)) {
$item();
} else {
print "No such function: $item\n";
}
}
ghoti#pc:~$ ./functest.php
one
two
three
No such function: four
ghoti#pc:~$
You need to check if the function exists or not:
function contr_val($key,$val) {
if (!function_exists($key)) {
function $key($val=NULL) {
if ($val)
$this->_$key = $val;
}
}
else {
return $this->_$key;
}
}

How to assign an object function to a variable?

class example()
{
function shout($var)
{
echo 'shout'.$var;
}
function whisper($var, $bool)
{
if($bool)
{
echo $var;
}
}
}
$obj = new example();
if($var)
{
$func = $obj->shout();
}else
{
$func = $obj->whisper();
}
I want to prepare the function variable first for later use instead of putting conditions in a loop. Is there a possible way to do it?
You can call methods by name:
if ($var) {
$fn = 'shout';
} else {
$fn = 'whisper';
}
$obj->$fn();
You can put the function name in a string:
if($var)
{
$func = 'shout';
}else
{
$func = 'whisper';
}
Later on:
$obj->$func
You can also use a callback:
if($var)
{
$func = array($obj, 'shout');
}else
{
$func = array($obj, 'whisper');
}
Later:
call_user_func($func);
or:
call_user_func_array($func, $args);

is it possible check if given function is executing within other function or method?

function echo_parent_func() {
echo // so what now ?
}
function somefunc() {
echo_parent_func();
}
somefunc(); //should echo string 'somefunc'
Is that even possible with php ?
function get_caller_method()
{
$traces = debug_backtrace();
if (isset($traces[2]))
{
return $traces[2]['function'];
}
return null;
}
function echo_parent_func() {
echo get_caller_method();
}
function somefunc() {
echo_parent_func();
}
somefunc(); //should echo string 'somefunc'
Source
EDIT Just found this answer too:

How to return a function by another function

I intend to create a checker function which will be used by another functions. The idea was simple: if the conditions are not fulfilled, stop the function by returning it.
This is the original code:
function awesome(){
$a = "2";
if ($a != "1"){return;}
echo "awesome";
}
It worked. Because the $a was 2, the function is returned and the word "awesome" is not appeared. However, there are several functions to check. To avoid repetition, i made it this way:
function test($var){
if ($var != "1"){return;}
}
function awesome(){
test("2");
echo "awesome";
}
function awesomeagain(){
test("3");
echo "awesome";
}
but the word "awesome"s are appeared, and the both function awesome() and awesomeagain() are not returned. How to return those two by adding test() function?
Thank you. I really appreciate your help.
Your test function has to return a value, and you have to test this value in other functions. Something like this:
function test($var) {
if ($var != "1")
return false;
else
return true;
}
so, your code should be like this:
function awesome() {
if (test("2"))
echo "awesome";
}
But, if you want to avid checks, you can throw an exception. This should look like this:
function test($var) {
if ($var != "1")
throw new Exception();
}
and in other functions use
function awesome() {
try {
test("2");
echo "yeah";
} catch ($e) {}
}
function test( $var ) {
return ( $var == "1" );
}
function awesome() {
if ( test("2") ) {
echo "awesome";
}
}
function awesomeagain(){
if ( test("3") ) {
echo "awesome";
}
}
Fikry, try to re-learn the concept of conditional, this is the basic programming skill. Without it, you will make many buggy code and functions.
to return from the function you have to use return keyword
function test($var){
if ($var == "1"){
return TRUE;
}
}
function awesome(){
if (!test("2")){
return FALSE;
}
echo "awesome";
return TRUE;
}
fYou probably shouldn't rely on another function stopping another function form running. Try this instead
function test($var){
if ($var != "1"){return false;} return true;
}
function awesome(){
if(test("2"))
echo "awesome";
}
function awesomeagain(){
if(test("3"));
echo "awesome";
}
function test($var) {
if ($var != "1"){
return "awesome";
}
// do something else when $var is not "1" here.
}
function awesome(){
echo test("2");
}
function awesomeagain(){
echo test("3");
}
That's it! PHP is awesome! :)

Categories