Function - Need Help Accessing a PHP Variable Variable Scope amp Globals

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m learning about PHP and I need some help on a global variable/scope problem. I need to access the value of $myvars in the outer function:

function outer() {
   function inner($atts) {
       $myvars = $atts[ mydata ];
   }
   // I need to access the value of $myvars in here:
   $jsonized = json_encode($myvars);
}

function set_atts_func($atts) {
    inner($atts);
}

add_shortcode("my_short_code", "set_atts_func");

I ve simplified the problem as much as I can. This is part of a WordPress plugin. I ve tried making $myvars global as follows:

function inner($atts) {
    global $myvars;
    $myvars = $atts[ mydata ];
}

But, I haven t figured it out. Any suggestions?


Additional Info:

If someone has a better way of solving my problem than using nested functions, I d love to hear it.

This is for a WordPress plugin for my site. In short, I need to pass the $atts to a javascript script.

Long Story: The add_shortcode() line calls set_att_func() and gives me access to the $atts. In order to pass $atts to the js, I ll use WordPress wp_localize_script() function.

But, this function can only be called where the script parameter referenced in wp_localize_script() call has been enqueued in wp_enqueue_script()-- at least as far as I can tell. I ve tried moving the wp_localize_script() and wp_enqueue_script() calls to set_atts_func() without any luck. So, I m trying to get $atts into outer(), where the wp_localize_script() and wp_enqueue_script() calls are.

If there is a simpler and easier way to access $atts in outer(), let me know.

Answers

I have mostly worked on object oriented approach and in this, the variable which u want to define as global, should be declared on top of the functions definitions like this.

> var $x;  
function myfunc($x)  
{  
$this->x =  dd ;    
}  

and when u will make the instance of the class u can simply call that variable x after the function myfunc() and its value will be dd. may u will have an idea.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8192543/need-help-accessing-a-php-variable-variable-scope-globals

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils