Search code examples
phppublic-method

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?


Solution

  • 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.