2013-09-25 213 views
2

下面是我的实际代码编辑版本:传递变量 - PHP

<?php 

include ('login_info.php'); 

class modernCMS { 

var $host; 
var $username; 
var $password; 
var $db; 
var $url; 


function connect(){ 
    $con = mysql_connect($this->host, $this->username, $this->password); 
    mysql_select_db($this->db, $con) or die(mysql_error()); 

mysql_set_charset('utf8'); 

} 


function get_coordinates(){ 

$sql ="select lat, lng from postcodes LIMIT 1;"; 
    $res = mysql_query($sql) or die(mysql_error()); 
    while($row = mysql_fetch_assoc($res)){ 
     $lat = $row['lat']; 
     $lng = $row['lng']; 

    } 
} 


function get_name(){ 

$sql ="select name from places WHERE lat=$lat AND lng=$lng LIMIT 1;"; 
    $res = mysql_query($sql) or die(mysql_error()); 
    while($row = mysql_fetch_assoc($res)){ 
     $name = $row['name']; 

echo $name; 


    } 
} 


?> 

然后一个单独的文件中我有一个包括用于上述的文件。我打电话使用功能得到名称如下:

<?=$obj->get_name()?> 

GET_NAME实际上包含了但是计算两个点之间的距离计算,因为它是一个耗时的计算我已经离开它的例子以上。

其重要的,我可以只使用obj- $> GET_NAME()来获取输出$ lat和$ LNG做的

+1

你可以将它们作为参数 – Ibu

+1

如果你需要一个getter和setter,创建一个坐标对象。 PHP是一种OOP语言:-) –

+0

您需要了解[variable scope](http://php.net/manual/en/language.variables.scope.php)。但是,使用诸如参数,返回值,数组,对象和属性之类的东西都比使用全局变量更可取。 – Sammitch

回答

2

您正在运行到一个作用域的问题。变量仅适用于声明它们的函数。为了使它们可用,你可以将变量明确地传递给函数(你需要确保始终在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 ScopeClasses 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注入”的查询是脆弱的。这里没什么大不了的,因为数据来自您的其他查询,但仍然不要直接在查询字符串中使用参数。

+0

这个例子让我感到困惑,因为你似乎在两个函数之外设置了值。在第一个函数中设置值的重要性在于它们来自sql语句。 –

+0

我会在代码中添加一些注释以尝试使其更易于理解。 –

+0

我已添加评论,希望能够更好地解释发生的事情。虽然只有这么一个简短的答案,但只有这么多。阅读我最后提到的两个文件将是最好的方式来充分理解正在发生的事情。不要被文档长度拖延,这不是一开始就很容易理解的,但是范围和类/对象都是一个重要的学习主题。 –

1

方式一:

function get_coordinates(&$lat, &$lng) 
{ 
    $lat = 25; 
    $lng = 5; 
} 

function display_coordinates($lat, $lng) 
{ 
    echo $lat; 
    echo $lng; 
} 

$lat = 0; 
$lng = 0; 

// assign values to variables 
get_coordinates($lat, $lng); 

// use function to display them... 
display_coordinates ($lat, $lng); 
3

功能的功能范围内运行,因此您在get_coordinates()中设置的变量是局部变量。要创建全局变量,你可以使用全局关键字:

<?php 

function get_coordinates() 
{ 
global $lat, $lng; 
$lat = 25; 
$lng = 5; 
} 

function display_coordinates() 
{ 
global $lat, $lng; 
echo $lat; 
echo $lng; 
} 

get_coordinates(); 
display_coordinates(); 

或者$GLOBALS阵列:

<?php 

function get_coordinates() 
{ 
$GLOBALS['lat'] = 25; 
$GLOBALS['lng'] = 5; 
} 

function display_coordinates() 
{ 
echo $GLOBALS['lat']; 
echo $GLOBALS['lng']; 
} 

get_coordinates(); 
display_coordinates(); 

然而,这可能不是设置/最好的方式访问这些变量,因为任何功能可以改变他们的状态在任何时候,你必须调用一个函数来设置它们,然后再调用另一个来显示它们。如果你能描述你的具体目标,你可能会得到更好的建议。

一个更好做到这一点的方法是使用一类,并通过在你需要它的对象(这个简单的例子不能证明正确encapsulation,但它是一个很好的起点):

<?php 

class Coordinates { 
    public $lat; 
    public $lng; 

    public function __construct($lat, $lng) { 
    $this->lat = $lat; 
    $this->lng = $lng; 
    } 

    public function display_coordinates() { 
    echo $this->lat . "\n"; 
    echo $this->lng . "\n"; 
    } 
} 

function get_coordinates() { 
    return new Coordinates(25, 5); 
} 

$coords = get_coordinates(); 
$coords->display_coordinates(); 


function output_coordinates($coordinates) { 
    $coordinates->display_coordinates(); 
} 
output_coordinates($coords); 

PHP中常用的另一种方法是在关联数组(包含索引字符串的数组)中传递事物。我不通常喜欢这一点,因为阵列并没有声明什么打算持有,但它是一个选项:

<?php 

function get_coordinates() { 
    return array('lat' => 25, 'lng' => 5); 
} 

function output_coordinates($coordinates) { 
    echo $coordinates['lat'] . '\n'; 
    echo $coordinates['lng'] . '\n'; 
} 

$coords = get_coordinates(); 
output_coordinates($coords); 
+0

是类和对象自动*更好*? – 2013-09-25 23:24:13

+0

@ Dagon不?我也不是故意暗示这一点。但是它有助于依赖性,封装和责任,因为您将相似的属性和方法组合在一起,消除了记住全局空间(以及在什么点)的负担。这段代码不是更长或更复杂,而是更有组织,更容易扩展。 – Nicole

+0

其尖叫的大胆,让我,但没有包子的斗争意图;-) – 2013-09-25 23:31:17

0

创建Coordinate.class.php文件:

<?php 
class Coordinate { 
    var $latitude; 
    var $longitude; 

    public function getLatitude() { 
    return $this->latitude; 
    } 

    protected function setLatitude($latitude) { 
    $this->latitude = floatval($latitude); 
    } 

    public function getLongitude() { 
    return $this->longitude; 
    } 

    protected function setLongitude($longitude) { 
    $this->longitude = floatval($longitude); 
    } 

    public function __construct() { 
    // Overload 
    if (func_num_args() == 2) { 
     $this->setLatitude(func_get_arg(0)); 
     $this->setLongitude(func_get_arg(1)); 
    } 
    // Default 
    else { 
     $this->setLatitude(0); 
     $this->setLongitude(0); 
    } 
    } 

    public function displayCoordinate() { 
    printf("Latitude: %.2f, Longitude: %.2f\n", 
     $this->getLatitude(), 
     $this->getLongitude()); 
    } 
} 

function main() { 
    $c = new Coordinate (25, 5); 
    $c->displayCoordinate(); 
} 

main(); 
?> 
0

另一个岗位的变化。我认为更好的办法:

function get_coordinates() 
{ 
    return array(
     "lat" => 25, 
     "lng" => 5 
    ); 

} 

function display_coordinates($latLongArray) 
{ 
    echo $latLongArray['lat']; 
    echo $latLongArray['lng']; 
} 


// assign values to variables 
$latLongArray = get_coordinates(); 

// use function to display them... 
display_coordinates ($latLongArray);