amin gholami
amin gholami

Reputation: 461

public variables in php

I have this function:

function map(){          
        $address = mashhad; // Google HQ
        $prepAddr = str_replace(' ','+',$address);
        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
        $output= json_decode($geocode);
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng;
        $ogt=owghat($month , $day , $longitude , $latitude  , 0 , 1 , 0);
}

and i need to use form $ogt in another function,is it possible that declared ogt as a public variable and if it possible how can i do that?

Upvotes: 2

Views: 79

Answers (3)

Evadecaptcha
Evadecaptcha

Reputation: 1451

You can set it as a global in the function:

function map() {
    //one method of defining globals in a function
    $GLOBALS['ogt'] = owghat($moth, $day, $longitude, $latitude, 0, 1, 0);
    // OR
    //the other way of defining a global in a function
    global $ogt;
    $ogt = owghat($month, $day, $longitude, $latitude, 0, 1, 0);
}

BUT this isn't the way you should go about this. If we want a variable from a function we just return it from the function:

function map() {
    $ogt = owghat($month, $day, $longitude, $latitude, 0, 1, 0);
    return $ogt;
}

$ogt = map(); //defined in global scope.

Upvotes: 1

Jesse Williams
Jesse Williams

Reputation: 662

If you declare $ogt outside of that function, it will be global to the work you are doing. You could also call a function from map() with $ogt as part of the call. It really depends on what you are doing. You can also just declare the variable as public as you could in C#. I would recommend this from the PHP manual:

http://php.net/manual/en/language.oop5.visibility.php

http://php.net/manual/en/language.variables.scope.php

Upvotes: 2

Samit Khulve
Samit Khulve

Reputation: 164

you can declare $ogt variable as global variable

Source:

1: http://php.net/manual/en/language.variables.scope.php

2: http://php.net/manual/en/reserved.variables.globals.php

Upvotes: 0

Related Questions