您正在运行到一个作用域的问题。变量仅适用于声明它们的函数。为了使它们可用,你可以将变量明确地传递给函数(你需要确保始终在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