您正在運行到一個作用域的問題。變量僅適用於聲明它們的函數。爲了使它們可用,你可以將變量明確地傳遞給函數(你需要確保始終在display_coordinates()
之前調用get_coordinates()
,否則你將會有未定義的值),或者使用全局變量(壞主意)。
最好的方法可能是爲它做一個類(儘管這取決於你打算如何使用它)。您的變量始終處於範圍內,並且在初始化變量之前,您不會冒試圖運行display_coordinates()
函數的風險。
class Coordinate
{
// These are the variables where the coords will be stored.
// They are available to everything within the {}'s after
// "class Coordinate" and can be accessed with
// $this->_<varname>.
protected $_lat;
protected $_long;
// This is a special function automatically called when
// you call "new Coordinate"
public function __construct($lat, $long)
{
// Here, whatever was passed into "new Coordinate" is
// now stored in our variables above.
$this->_lat = $lat;
$this->_long = $long;
}
// This takes the values are stored in our variables,
// and simply displays them.
public function display()
{
echo $this->_lat;
echo $this->_long;
}
}
// This creates a new Coordinate "object". 25 and 5 have been stored inside.
$coordinate = new Coordinate(25, 5); // 25 and 5 are now stored in $coordinate.
$coordinate->display(); // Since $coordinate already "knows" about 25 and 5
// it can display them.
// It's important to note, that each time you run "new Coordinate",
// you're creating an new "object" that isn't linked to the other objects.
$coord2 = new Coordinate(99, 1);
$coord2->display(); // This will print 99 and 1, not 25 and 5.
// $coordinate is still around though, and still knows about 25 and 5.
$coordinate->display(); // Will still print 25 and 5.
你應該閱讀了關於Variable Scope和Classes and Objects更瞭解這一點。
與原來的代碼放在一起把這個,你會做這樣的事情,
function get_coordinates()
{
return new Coordinate(25, 5);
}
function display_coordinates($coord)
{
$coord->display();
}
$c = get_coordinates();
display_coordinates($c);
// or just "display_coordinates(get_coordinates());"
問題更新
有代碼中的一些不良做法後編輯,但這裏有一些快速的步驟來獲得你想要的。
// Copy the Coordinate class from my answer above, but add two new
// lines before the final "}"
public function getLatitude() { return $this->_lat; }
public function getLongitude() { return $this->_long; }
// Put the Coordinate class definition before this line
class modernCMS {
/////
// In your code, after this line near the top
var $url;
// Add this
var $coord;
/////
// In your get_coordinates(), change this...
$lat = $row['lat'];
$lng = $row['lng'];
// To this...
$this->coord = new Coordinate($lat, $lng);
/////
// In your get_name(), add two lines to the start of your function.
function get_name(){
$lat = $this->coord->getLatitude();
$lng = $this->coord->getLongitude();
無關你的問題,但你也應該在get_name()
閱讀「SQL注入」的查詢是脆弱的。這裏沒什麼大不了的,因爲數據來自您的其他查詢,但仍然不要直接在查詢字符串中使用參數。
你可以將它們作爲參數 – Ibu
如果你需要一個getter和setter,創建一個座標對象。 PHP是一種OOP語言:-) –
您需要了解[variable scope](http://php.net/manual/en/language.variables.scope.php)。但是,使用諸如參數,返回值,數組,對象和屬性之類的東西都比使用全局變量更可取。 – Sammitch