Chris
Chris

Reputation: 997

How do I access a variable in a function without passing it?

I looked around but can't really find anything. I tried using global but I think I am using it wrong.

function testing() {
    $a = (object) array('a' => 100, 'b' => 200);
    function test2(){
        global $a;
        var_dump($a);
    }
    test2();
}
testing();

I want to be able to get $a inside test2() without passing the variable as parameter.

EDIT: Thank you for the comments and answers. The examples work however in my specific case it does not seem to work. I wrote this little function at the top of my view, then call it when I need it.

var_dump($data); // DATA here is fine - I need it in the function
function getDataVal($data_index) {
    return (isset($data->{$data_index}))?$data->{$data_index}:'';
}

I then call it on the page a bit later like this:

<input type="text" id="something" value="<?=getDataVal('something')?>" />

I know I can just pass $data in the request, however I was hoping there was an easier way to access data inside that function.

Upvotes: 1

Views: 2609

Answers (2)

hherger
hherger

Reputation: 1680

global means "global", e.g. a variable defined in the global namespace.

I don't know why you are trying to avoid passing the variable as a parameter. My guess: it should be writeable, and it usually is not.

These are two variants of the same solution:

<?php


// VARIANT 1: Really globally defined variable
$a = false; // namespace: global

function testing1() {
    global $a;
    $a = (object) array('a' => 100, 'b' => 200);

    function test1(){
        global $a;
        echo '<pre>'; var_dump($a); echo '</pre>'; 
    }
    test1();
}
testing1();


// VARIANT 2: Passing variable, writeable
function testing2() {
    $a = (object) array('a' => 100, 'b' => 200);

    function test2(&$a){ // &$a: pointer to variable, so it is writeable
        echo '<pre>'; var_dump($a); echo '</pre>'; 
    }
    test2($a);
}
testing2();


}
testing();

Result, both variants:

object(stdClass)#1 (2) {
  ["a"]=> int(100)
  ["b"]=> int(200)
}

object(stdClass)#2 (2) {
  ["a"]=> int(100)
  ["b"]=> int(200)
}

Upvotes: 4

mitkosoft
mitkosoft

Reputation: 5316

Define it as global variable:

    a = array();
    function testing() {
        global $a;
        $a = (object) array('a' => 100, 'b' => 200);
        function test2(){
            global $a;
            var_dump($a);
        }
        test2();
    }

testing();

Edit Missing $ in global a

Upvotes: 0

Related Questions