I'm having difficulty passing some variables from one function to another.
I've tried to make them global with little success.
The variables I would like to pass are the ones from send_email_notifications to send_email_notification_function.
function send_email_notifications($ID, $post) {
global $notificationTitle;
global $notificationPermalink;
$notificationTitle = $post->post_title;
$notificationPermalink = get_permalink($ID);
if(isset($_REQUEST['send_email_notification'])) {
date_default_timezone_set('Europe/London');
wp_schedule_single_event(time() + 10, 'send_email_notification_function_execute');
}
}
add_action('publish_Test_notifications', 'send_email_notifications', 10, 2);
function send_email_notification_function() {
global $notificationTitle;
global $notificationPermalink;
echo $notificationTitle;
echo $notificationPermalink;
$notificationEmail = 'test#test.com';
wp_mail($notificationEmail, $notificationSubject, $notificationContent);
}
add_action('send_email_notification_function_execute', 'send_email_notification_function');
It seems you are using wordpress. Your question might be better answered on https://wordpress.stackexchange.com/.
You should use an object instead of a function for the callable parameter of add_action. Your object can contain your global variables.
For example you can create a php class called EmailNotification and it can have two functions send_email_notification_function and send_email_notifications. This class can have two properties called $notificationTitle and $notificationPermalink.
You can then create an instance of this class and use it as the second argument to add_action.
Related
I created a class. The code is below
class Another {
public $error = array();
public function set_error( $key, $value )
{
if ( isset( $key ) ) {
$sanitizedKey = sanitize_key( $key );
$this->error[ $sanitizedKey ] = wp_json_encode( $value );
return $this->error;
}
}
public function get_error( $id )
{
if ( ! is_null( $id ) ) {
return $this->error[ $id ];
}
}
public function print_error()
{
if ( $this->error ) {
foreach ($this->error as $key => $value) {
$decodeJson = json_decode( $value );
?>
<div class="ud-error">
<p class="ud-error-<?php echo $key; ?>">
<?php echo __( $decodeJson, 'ud-for-edd' ); ?>
</p>
</div>
<?php
}
}
}
}
If I invoke it in the following way it works. It echos the content as expected.
$error = new Another();
$error->set_error('gg', 'hhhh');
$error->print_error();
But if I use it with function then it doesn't work as expected. Do I have to pass parameters by reference or any other? The following way it doesn't work
function create_error($id, $val) {
$errr = new Another();
return $errr->set_error($id, $val);
}
create_error('raa', 'raashid');
$error = new Another();
$error->print_error();
I am confused about why this doesn't work. Any clue. Thanks in advance.
Steps I want the code to perform:
Create a class with 3 methods, set_error, get_error, and print_error
Then invoke the class inside the function. The function will accept two parameters because inside the class the set_error() method accepts two parameters.
In order to print the error, I will instantiate the class and call the print_error() method.
In case, if I have to print the new error. I will just call the create_error() function to do this for me. Because the function needs 2 parameters. The arguments supplied to the function must be supplied as arguments to the set_error() method.
I hope the list helps.
Update:
If I use a global variable then it works. Below is working.
$customError = new Another();
function create_error($id, $val) {
global $customError;
$customError->set_error($id, $val);
}
create_error('raa', 'rashid');
$customError->print_error();
Thanks, #roggsFolly and #El_Vanja. By understanding your tips I was able to solve the error. If there is anything wrong with the code I just said worked. Please point out.
The object you instantiate inside the function is not the same one you try and print the error message from.
First the object you instantiate inside the function scope is not visible outside the function.
function create_error($id, $val) {
$errr = new Another();
return $errr->set_error($id, $val);
}
create_error('raa', 'raashid');
// this instantiates a seperate Another object from the one
// you created in the function
$error = new Another();
// this tries to print from the new object taht has no message stored in it yet
$error->print_error();
To instantiate the object inside a function scope and then use that object outside the function scope you must pass that object back to the caller of the function
function create_error($id, $val) {
$errr = new Another();
$errr->set_error($id, $val);
return $errr; // this returns the object
}
$error = create_error('raa', 'raashid');
// now you can use its methods to print the stored message
$error->print_error();
Update as per your additional Information
A couple of things I think you may be getting confused about.
Each time you do $var = new ObjectName; you are creating a brand new instance of that class. This new instance has no knowledge about any other instances of that class that may or may not have been created before or may be created after that point. And more specifically to your problems, it does not have access to the properties of another version of that object.
You are I believe missing the concept of variable scope. The Object you create inside that function, will only actually exist while the function is running. Once the function completes anything created/instantiated wholly within that function is DESTROYED ( well in truth it is just no longer accessible ) but to all intent and purpose it is destroyed. you therefore cannot expect to be able to address it outside the scope of the function.
If you want the Object you instantiate within the function to be usable outside the function, you must pass a reference to that object out of the function to the calling code. This passes that reference into the scope of the calling code and keeps the object alive, global scope in your case, but that might be another function or even another object. That allows you access to that instantiation and any properties that were set within it.
I created a php function and I want to clear/reset the arguments of the function.
for example I've got this function declared twice in my index.php:
grid_init($type='portfolio',$postNb=4,$rowNb=2);
grid_init($type='post',$postNb,$rowNb);
function grid_init($type,$postNb,$rowNb) {
?>
<div class="container" data-type="<?php echo $type; ?>" data-postNb="<?php echo $rowNb; ?>" data-rowNb="<?php echo $rowNb; ?>">
some stuff.....
</div>
<?php
}
If I didn't specified my argument in my second function (in the above example $postNb $rowNb), these vars will take the values of the previous argument declared in the previous function ($postNb=4,$rowNb=2)...
How can I reset/clear my argument in my function between each function declared in a same file?
To make a function have default arguments it's like:
function grid_init($type, $postNb = 2, $rowNb = 4){
echo "<div class='container' data-type='$type' data-postNb='$rowNb' data-rowNb='$rowNb'>".
"some stuff.....".
'</div>';
}
Execute like:
grid_init('whatever'); // will assume $postNb = 2 and $rowNb = 4;
grid_init('some_data_type', 42, 11); // overwrite your defaults
You seem to have trouble calling functions.
Change your calls to
grid_init('portfolio',4,2);
grid_init('post','',''); // or use '' as default
a) you might have declared a function like this
function grid_init($type, $postNb, $rowNb)
{
// do stuff on $tyoe, $postNb, $rowNb
}
b) you might call the function several times, each time with new parameters
grid_init('post', 5, 4);
grid_init('somewhere', 1, 2);
A function does not memorize values of prior calls.
If you want that, then save them somewhere from within that function.
c) you might use default parameters on your function
Default parameters always come last in the function declaration.
function grid_init($type, $postNb = 2, $rowNb = 2)
{
// do stuff on $tyoe, $postNb, $rowNb
}
call it
grid_init('somewhere');
now postNb, rowNb are not set, but the default values from the declaration are used.
d) keep the number of parameters low!
I have a function in one of my views, and I want to access one of the variables available to the view through CodeIgniter's data array.
For example; in my controller I have this:
$this->load->view('someview', array(
'info' => 'some info'
));
Now, within my view, I have a function, and I want to be able to access the variable $info from within that function scope.
Is that possible?
in your controller:
$GLOBALS['var_available_in_function'] = $value;
Your function:
function get_var() {
global $var_available_in_function;
return $var_available_in_function;
}
I tried this but using globals in my view someview.php doesn't work..
function func_in_view(){
global $info;
print_r ($info); // NULL
}
You may need to pass this as a parameter instead to your function so it's available to it.
function func_in_view($info){
print_r ($info); // NULL
}
I read this method $this->load->vars($array)
in http://codeigniter.com/user_guide/libraries/loader.html
but it's purpose is just to make it available to any view file from any function for that controller. I tried my code above global $info; and it still doesn't work.
You may need to do the workaround by passing it as a parameter instead.
Try including this in your someview.php => print "<pre>";print_r($GLOBALS);print "</pre>"; and the variables passed through $this->load->view aren't included.
I solved this by creating a global variable within the view, then assigning the passed in $data value to the global variable. That way, the information can be read within the view's function without having to pass the variable to the function.
For example, in the controller, you have:
$data['variable1'] = "hello world";
$this->load->view('showpage',$data);
Then in the showpage.php view, you have:
global $local_variable = $variable1;
function view_function() {
global $local_variable;
echo $local_variable;
}
view_function();
Hope this helps!
I will explain the question with a simple function accepting any number of function
function abc() {
$args = func_get_args();
//Now lets use the first parameter in something...... In this case a simple echo
echo $args[0];
//Lets remove this first parameter
unset($args[0]);
//Now I want to send the remaining arguments to different function, in the same way as it received
.. . ...... BUT NO IDEA HOW TO . ..................
//tried doing something like this, for a work around
$newargs = implode(",", $args);
//Call Another Function
anotherFUnction($newargs); //This function is however a constructor function of a class
// ^ This is regarded as one arguments, not mutliple arguments....
}
I hope the question is clear now, what is the work around for this situation?
Update
I forgot to mention that the next function I am calling is a constructor class of another class.
Something like
$newclass = new class($newarguments);
for simple function calls
use call_user_func_array, but do not implode the args, just pass the array of remaining args to call_user_func_array
call_user_func_array('anotherFunction', $args);
for object creation
use: ReflectionClass::newInstanceArgs
$refClass = new ReflectionClass('yourClassName');
$obj = $refClass->newInstanceArgs($yourConstructorArgs);
or: ReflectionClass::newinstance
$refClass = new ReflectionClass('yourClassName');
$obj = call_user_func_array(array($refClass, 'newInstance'), $yourConstructorArgs);
I'm playing around with hooking into functions, the hook will call the method of another object, what is the best way of changing the value $price in the parent function before it is returned?
function _product_price ($price,$taxable = true)
{
$shop->_hook('PRODUCT_PRICE_BEFORE');
$price = 100.00;
$shop->_hook('PRODUCT_PRICE_AFTER');
return number_format($price,2);
}
Thanks guys, would this be a suitable solution?
function _product_price ($price,$taxable = true)
{
global $shop;
$shop->_hook('PRODUCT_PRICE_BEFORE');
$price = 100.00;
$shop->passedArgs['price'] = $price;
$shop->_hook('PRODUCT_PRICE_AFTER');
return number_format($shop->passedArgs['price'],2);
}
function _hook ()
{
global $shop;
$shop->passedArgs['price'] = 23.00;
return;
}
Since you likely want to register arbitrary methods for hooks, have a look at
Subject/Observer and
Event Dispatcher
I'd pass the variables to the point either:
as an array of references, (array('price' => &$price); would make any change to the $var['price'] variable in a function later on / deeper reflect in the 'in-scope' $price.
set the variables to the point as an object-property and just pass the current observable object as a parameter.