public php 中的变量
public variables in php
我有这个功能:
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);
}
我需要在另一个函数中使用 $ogt 形式,是否可以将 ogt 声明为 public 变量,如果可能的话我该怎么做?
您可以将 $ogt 变量声明为全局变量
来源:
可以在函数中设置为全局:
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);
}
但是 这不是您应该采用的方式。如果我们想要一个函数中的变量,我们只需 return 它来自函数:
function map() {
$ogt = owghat($month, $day, $longitude, $latitude, 0, 1, 0);
return $ogt;
}
$ogt = map(); //defined in global scope.
如果您在该函数之外声明 $ogt
,它将对您所做的工作具有全局性。您还可以使用 $ogt
从 map()
调用函数作为调用的一部分。这真的取决于你在做什么。您也可以像在 C# 中那样将变量声明为 public。我会从 PHP 手册中推荐这个:
我有这个功能:
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);
}
我需要在另一个函数中使用 $ogt 形式,是否可以将 ogt 声明为 public 变量,如果可能的话我该怎么做?
您可以将 $ogt 变量声明为全局变量
来源:
可以在函数中设置为全局:
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);
}
但是 这不是您应该采用的方式。如果我们想要一个函数中的变量,我们只需 return 它来自函数:
function map() {
$ogt = owghat($month, $day, $longitude, $latitude, 0, 1, 0);
return $ogt;
}
$ogt = map(); //defined in global scope.
如果您在该函数之外声明 $ogt
,它将对您所做的工作具有全局性。您还可以使用 $ogt
从 map()
调用函数作为调用的一部分。这真的取决于你在做什么。您也可以像在 C# 中那样将变量声明为 public。我会从 PHP 手册中推荐这个: