Access to a variable function from another function in WordPress - php

there's a problem, I can not understand what I'm doing wrong ..
I want to get the value of the function of the other features in WordPress ..
This code replaces some parts of the code ..
I want to get the value of the argument variable words (it needs to go $attr['words']) and then use the other functions (new_quote).
<?php
/*
* Plugin Name: Random Quotes
*/
function random_quote($atts) {
extract( shortcode_atts( array(
'path' => plugin_dir_path(__FILE__).'quotes.txt',// default, if not set
'label_new' => 'New Quote',
'words' => 'no' // yes or no
), $atts ) );
$temp = $attr['words']; // no
...
}
add_shortcode('randomquotes','random_quote');
function new_quote(){
global $temp; // NULL
/*
global $attr;
$temp = $attr['words']; // again NULL
*/
...
if($temp == "no") {
...
}
}
...
?>
What am I doing wrong? Maybe just can not get the value of this variable?

It looks like you need to declare global $temp within your random_quote() function. Right now, random_quote() is using a local version of $temp, which is lost when the function is completed.
EDIT: Here's an example snippet
<?php
function test() {
global $temp;
$temp = 'no';
}
function my_test() {
global $temp;
var_dump($temp);
}
test();
my_test();
?>

Related

Is it possible to pass a function as another function parameter? [duplicate]

I need to pass a function as a parameter to another function and then call the passed function from within the function...This is probably easier for me to explain in code..I basically want to do something like this:
function ($functionToBeCalled)
{
call($functionToBeCalled,additional_params);
}
Is there a way to do that.. I am using PHP 4.3.9
Thanks!
I think you are looking for call_user_func.
An example from the PHP Manual:
<?php
function barber($type) {
echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
function foo($function) {
$function(" World");
}
function bar($params) {
echo "Hello".$params;
}
$variable = 'bar';
foo($variable);
Additionally, you can do it this way. See variable functions.
In php this is very simple.
<?php
function here() {
print 'here';
}
function dynamo($name) {
$name();
}
//Will work
dynamo('here');
//Will fail
dynamo('not_here');
I know the original question asked about PHP 4.3, but now it's a few years later and I just wanted to advocate for my preferred way to do this in PHP 5.3 or higher.
PHP 5.3+ now includes support for anonymous functions (closures), so you can use some standard functional programming techniques, as in languages like JavaScript and Ruby (with a few caveats). Rewriting the call_user_func example above in "closure style" would look like this, which I find more elegant:
$barber = function($type) {
echo "You wanted a $type haircut, no problem\n";
};
$barber('mushroom');
$barber('shave');
Obviously, this doesn't buy you much in this example - the power and flexibility comes when you pass these anonymous functions to other functions (as in the original question). So you can do something like:
$barber_cost = function($quantity) {
return $quantity * 15;
};
$candy_shop_cost = function($quantity) {
return $quantity * 4.50; // It's Moonstruck chocolate, ok?
};
function get_cost($cost_fn, $quantity) {
return $cost_fn($quantity);
}
echo '3 haircuts cost $' . get_cost($barber_cost, 3) . "\n";
echo '6 candies cost $' . get_cost($candy_shop_cost, 6) . "\n";
This could be done with call_user_func, of course, but I find this syntax much clearer, especially once namespaces and member variables get involved.
One caveat: I'll be the first to admit I don't know exactly what's going on here, but you can't always call a closure contained in a member or static variable, and possibly in some other cases. But reassigning it to a local variable will allow it to be invoked. So, for example, this will give you an error:
$some_value = \SomeNamespace\SomeClass::$closure($arg1, $arg2);
But this simple workaround fixes the issue:
$the_closure = \SomeNamespace\SomeClass::$closure;
$some_value = $the_closure($arg1, $arg2);
You could also use call_user_func_array(). It allows you to pass an array of parameters as the second parameter so you don't have to know exactly how many variables you're passing.
If you need pass function with parameter as parameter, you can try this:
function foo ($param1){
return $param1;
}
function bar ($foo_function, $foo_param){
echo $foo_function($foo_param);
}
//call function bar
bar('foo', 'Hi there'); //this will print: 'Hi there'
phpfiddle example
Hope it'll be helpful...
If you want to do this inside a PHP Class, take a look at this code:
// Create a sample class
class Sample
{
// Our class displays 2 lists, one for images and one for paragraphs
function __construct( $args ) {
$images = $args['images'];
$items = $args['items'];
?>
<div>
<?php
// Display a list of images
$this->loop( $images, 'image' );
// notice how we pass the name of the function as a string
// Display a list of paragraphs
$this->loop( $items, 'content' );
// notice how we pass the name of the function as a string
?>
</div>
<?php
}
// Reuse the loop
function loop( $items, $type ) {
// if there are items
if ( $items ) {
// iterate through each one
foreach ( $items as $item ) {
// pass the current item to the function
$this->$type( $item );
// becomes $this->image
// becomes $this->content
}
}
}
// Display a single image
function image( $item ) {
?>
<img src="<?php echo $item['url']; ?>">
<?php
}
// Display a single paragraph
function content( $item ) {
?>
<p><?php echo $item; ?></p>
<?php
}
}
// Create 2 sample arrays
$images = array( 'image-1.jpg', 'image-2.jpg', 'image-3.jpg' );
$items = array( 'sample one', 'sample two', 'sample three' );
// Create a sample object to pass my arrays to Sample
$elements = { 'images' => $images, 'items' => $items }
// Create an Instance of Sample and pass the $elements as arguments
new Sample( $elements );

make array keys available defined in one function available to second function

Can't seem to make this work.
I want to make the array below available to a second function but it always comes up empty
The main code is this:
function GenerateSitemap($params = array()) {
$array = extract(shortcode_atts(array(
'title' => 'Site map',
'id' => 'sitemap',
'depth' => 2
), $params));
global $array;
}
function secondfunction()
{
global $array;
print $title;
// this function throws an error and can't access the $title key from the first function
}
GenerateSitemap()
secondfunction()
I'd like to use the title, id or depth KEYS inside a second function. They just come up empty and throw an error
"The scope of a variable is the context within which it is defined."
http://us3.php.net/language.variables.scope.php
You need to define the variable (at least initially) outside the function:
$array = array();
function GenerateSitemap($params = array()) {
global $array;
$array = extract(shortcode_atts(array(
'title' => 'Site map',
'id' => 'sitemap',
'depth' => 2
), $params));
}
function SecondFunction() {
global $array;
...
}
You need to declare the variable as global before you use it inside the function, otherwise it will implicitly create a local variable.
function myFunc() {
global $myVar;
$myVar = 'Hello World';
}
myFunc();
print_r($myVar); // 'Hello World'
You don't actually have to declare it initially in the globalscope, you will not get a notice/warning/error, although it is obviously good practice to do so. (Although if good practice is the goal then you probably shouldn't be using global variables to begin with.)

Can I add a variable value to a passed function parameter in php?

I have the following variable:
$argument = 'blue widget';
Which I pass in the following function:
widgets($argument);
The widgets function has two variables in it:
$price = '5';
$demand ='low';
My questions is how can I do the following:
$argument = 'blue widget'.$price.' a bunch of other text';
widgets($argument);
//now have function output argument with the $price variable inserted where I wanted.
I don't want to pass $price to the function
price is made available once inside the function
Is there any sound way I can do this or do I need to rethink my design?
Off the top of my head, there are two ways to do this:
Pass in two arguments
widget($initText, $finalText) {
echo $initText . $price . $finalText;
}
Use a placeholder
$placeholder = "blue widget {price} a bunch of other text";
widget($placeholder);
function widget($placeholder) {
echo str_replace('{price}',$price,$placeholder);
}
// within the function, use str_replace
Here's an example: http://codepad.org/Tme2Blu8
Use some sort of placeholder, then replace it within your function:
widgets('blue widget ##price## a bunch of other text');
function widgets($argument) {
$price = '5';
$demand = 'low';
$argument = str_replace('##price##', $price, $argument);
}
See it here in action: http://viper-7.com/zlXXkN
Create a placeholder for your variables like this:
$argument = 'blue widget :price a bunch of other text';
in your widget() function, use a dictionary array and str_replace() to get your result string:
function widgets($argument) {
$dict = array(
':price' => '20',
':demand' => 'low',
);
$argument = str_replace(array_keys($dict), array_values($dict), $argument);
}
I would encourage preg_replace_callback. By using this method, we can easily use the captured values as a lookup to determine what their replacement should be. If we come across an invalid key, perhaps the cause of a typo, we can respond to this as well.
// This will be called for every match ( $m represents the match )
function replacer ( $m ) {
// Construct our array of replacements
$data = array( "price" => 5, "demand" => "low" );
// Return the proper value, or indicate key was invalid
return isset( $data[ $m[1] ] ) ? $data[ $m[1] ] : "{invalid key}" ;
}
// Our main widget function which takes a string with placeholders
function widget ( $arguments ) {
// Performs a lookup on anything between { and }
echo preg_replace_callback( "/{(.+?)}/", 'replacer', $arguments );
}
// The price is 5 and {invalid key} demand is low.
widget( "The price is {price} and {nothing} demand is {demand}." );
Demo: http://codepad.org/9HvmQA6T
Yes, you can. Use global inside your function.
$global_var = 'a';
foo($global_var);
function foo($var){
global $global_var;
$global_var = 'some modifications'.$var;
}
Consider changing the argument and then returning it from your widget function rather than simply changing it within the function. It will be more clear to people reading your code that $argument is being modified without having to read the function as well.
$argument = widget($argument);
function widget($argument) {
// get $price;
return $argument . $price;
}

How to get a strings data from a different function?

I have a php file with different functions in it. I need to get data from strings in a function, but the strings have been specified in a different function. How can this be done please?
... To clarify, I have two functions.
function a($request) { $username = ...code to get username; }
the username is over retreivable during function a.
function b($request) { }
function b need the username, but cannot retrieve it at the point its called, so need it from function a. I am very much a beginer here (so bear with me please), I tried simply using $username in function b, but that didn't work.
Can you please explain how I can do this more clearly please. There are another 5 strings like this, that function b needs from function a so I will need to do this for all the strings.
...Code:
<?php
class function_passing_variables {
function Settings() {
//function shown just for reference...
$settings = array();
$settings['users_data'] = array( "User Details", "description" );
return $settings;
}
function a( $request ) {
//This is the function that dynamically gets the user's details.
$pparams = array();
if ( !empty( $this->settings['users_details'] ) ) {
$usersdetails = explode( "\n", Tool::RW( $this->settings['users_data'], $request ) );
foreach ( $usersdetails as $chunk ) {
$k = explode( '=', $chunk, 2 );
$kk = trim( $k[0] );
$pparams[$kk] = trim( $k[1] );
}
}
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
//These variables will retrieve the details
}
function b( $request ) {
//Here is where I need the data from the variables
//$email=$pparams['data_email'];
//$name=$pparams['data_name'];
//$username=$pparams['data_username'];
}
}
?>
#A Smith, let me try to clarify what you mean.
You have several variables, example : $var1, $var2, etc.
You have two function (or more) and need to access that variables.
If that what you mean, so this may will help you :
global $var1,$var2;
function a($params){
global $var1;
$var1 = 1;
}
function b($params){
global $var1,$var2;
if($var1 == 1){
$var2 = 2;
}
}
Just remember to define global whenever you want to access global scope variable accross function. You may READ THIS to make it clear.
EDITED
Now, its clear. Then you can do this :
class function_passing_variables{
// add these lines
var $email = "";
var $name = "";
var $username = "";
// ....
Then in your function a($request) change this :
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
to :
$this->email=$pparams['data_email'];
$this->name=$pparams['data_name'];
$this->username=$pparams['data_username'];
Now, you can access it in your function b($request) by this :
echo $this->email;
echo $this->name;
echo $this->username;
In the functions where the string has been set:
Global $variable;
$variable = 'string data';
Although you really should be returning the string data to a variable, then passing said variable to the other function.

I failed at creating a simple language function, what am I doing wrong?

I tried to create a simple language function, but I can't get it to work. The idea should be clear. I'm not getting any error messages but it won't show my text either. This is my code:
inc/text.php:
<?php
$show = array(
"welcome" => "Welkom # ....",
'test' => true
);
function show($foo) {
echo $show[$foo];
}
?>
index.php:
<?php show("welcome"); ?>
Make $show array global scope within the function, and return the value not echo it
<?php
$show = array(
"welcome" => "Welkom # ....",
'test' => true
);
function show($foo) {
global $show;
return $show[$foo];
}
?>
<p><?php echo show("welcome"); ?></p>
It looks to me like you're declaring $show outside of the scope of function show($foo)
either declare $show inside the function or do this:
$show = array(); //blah blah
function show($foo)
{
global $show;
echo $show[$foo];
}
You need to declare the SHOW array, so it is accesible from the function.
You have sevral methods to do this
Global variable
Pass it like a parameter
Declare the array in a function
Example of declaration inside a function
function show($foo) {
$show = array(
"welcome" => "Welkom # ....",
'test' => true
);
echo $show[$foo];
}
You don't need a function for that:
<?php echo $show["welcome"]; ?>
That should already do it. Let me know if that is not helpful and why.

Categories