Вы бежите в вопрос определения масштабов. Переменные доступны только для функции, которая их объявила. Чтобы сделать их доступными, вы можете явно передать переменные функции (вам нужно всегда вызывать 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.
Вы должны прочитать на 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());"
Edit после вопроса обновляемой
Есть несколько плохих практик в вашем коде, но вот несколько быстрых шагов, чтобы получить то, что вы хотите.
// 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();
Unrelated на ваш вопрос, но вы также должны читать о «SQL Injection», как запрос в get_name()
уязвима. Здесь не так уж и много, поскольку данные поступают из вашего другого запроса в любом случае, но все же хорошая практика не использовать параметры непосредственно в строке запроса.
вы можете передать их в качестве параметров – Ibu
Если вам нужен геттер и сеттер, создать объект Coordinate. PHP - это язык ООП :-) –
Вам нужно узнать о [scope scope] (http://php.net/manual/en/language.variables.scope.php). Однако использование таких вещей, как аргументы, возвращает, массивы, объекты и свойства, все * MUCH * предпочтительнее использовать глобальные переменные. – Sammitch