您遇到了范围界定问题。这些变量仅对声明它们的函数可用。为了使它们可用,您可以将变量显式传递给函数(您需要确保get_coordinates()
之前总是调用display_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.
您应该阅读变量范围和类和对象以了解更多信息。
要将其与您的原始代码放在一起,您将执行以下操作,
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();
与您的问题无关,但您还应该阅读有关“SQL 注入”的信息,因为查询get_name()
很容易受到攻击。这里没什么大不了的,因为无论如何数据都来自您的其他查询,但仍然是不要直接在查询字符串中使用参数的好习惯。