在函数之间传递变量 - php [英] Passing variable between functions - php

查看:108
本文介绍了在函数之间传递变量 - php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的实际代码的修改版本:

 <?php 

include ( 'login_info.php');

class modernCMS {

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


函数connect(){
$ con = mysql_connect($ this->主机,$ this->用户名,$ this->密码);
mysql_select_db($ this-> db,$ con)或die(mysql_error());

mysql_set_charset('utf8');



$ b函数get_coordinates(){

$ sql =select post,lng from postcodes LIMIT 1;;
$ res = mysql_query($ sql)或者死(mysql_error());
while($ row = mysql_fetch_assoc($ res)){
$ lat = $ row ['lat'];
$ lng = $ row ['lng'];




$ b函数get_name(){

$ sql =从地点选择名称WHERE lat = $ lat AND lng = $ lng LIMIT 1;;
$ res = mysql_query($ sql)或者死(mysql_error());
while($ row = mysql_fetch_assoc($ res)){
$ name = $ row ['name'];

echo $ name;


}
}


?>

然后在一个单独的文档中,我有一个包含上面的文件。我使用以下方法调用函数get name:

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

get_name实际上包含计算两点之间距离的计算,但因为它有一个冗长的计算它不在上面的例子中。



重要的是,我可以使用$ obj-> get_name()来获取$ lat和$ lng的输出结果

解决方案

您遇到了一个范围问题。变量仅适用于声明它们的函数。为了使它们可用,可以将变量明确地传递给函数(您需要确保始终在 display_coordinates()之前调用 get_coordinates() 虽然,否则你会有未定义的值)或使用全局变量(坏主意)。

最好的方法可能是做一个它的类(虽然这取决于你打算如何使用它)。您的变量将始终在范围内,并且在初始化变量之前,您不会冒着尝试运行 display_coordinates()函数的风险。

 类坐标
{
//这些是coords存储的变量。
//它们可以在
//类坐标之后的{}之内使用,并且可以通过
// $ this-> _< varname>进行访问。
保护$ _lat;
保护$ _long;

//这是一个特殊的函数,当
//你调用new Coordinate时会自动调用
public function __construct($ lat,$ long)
{
//在这里,无论传递给新坐标的是
//现在存储在上面的变量中。
$ this-> _lat = $ lat;
$ this-> _long = $ long;
}

//这需要将这些值存储在我们的变量
中//并简单地显示它们。
public function display()
{
echo $ this-> _lat;
echo $ this-> _long;
}
}

//这将创建一个新的坐标对象。 25和5已经储存在里面。
$ coordinate = new Coordinate(25,5); // 25和5现在存储在$坐标中。
$ coordinate-> display(); //由于$坐标已经知道25和5
//它可以显示它们。

//重要的是要注意,每次运行新坐标时,
//您正在创建一个未链接到其他对象的新对象。
$ coord2 =新坐标(99,1);
$ coord2-> display(); //这将打印99和1,而不是25和5.

// $坐标仍然在,但仍然知道大约25和5.
$ coordinate-> display( ); //仍然会打印25和5.

您应该阅读变量范围 Classes and Objects 以了解更多关于此的信息。



为了将它和原始代码放在一起,像这样的事情,

 函数get_coordinates()
{
返回新坐标(25,5);
}

函数display_coordinates($ coord)
{
$ coord-> display();
}

$ c = get_coordinates();
display_coordinates($ c);
//或者只是display_coordinates(get_coordinates());




问题已更新



您的代码中存在一些不良做法,但您可以通过一些快速步骤来获得所需内容。

  //从上面的答案复制坐标类,但在最后一个}之前添加两个新的
行//
public function getLatitude(){返回$ this-> _lat; }
public function getLongitude(){return $ this-> _long; }

//将坐标类定义放在这一行之前
class modernCMS {

/////

// In你的代码,在这条线后面的
var $ url;

//添加此
var $ coord;

/////

//在你的get_coordinates()中,改变这个...
$ lat = $ row ['lat'];
$ lng = $ row ['lng'];

//对此...
$ this-> coord =新坐标($ lat,$ lng);

/////

//在您的get_name()中,将两行添加到函数的开头。
函数get_name(){
$ lat = $ this-> coord-> getLatitude();
$ lng = $ this-> coord-> getLongitude();

与您的问题无关,但您还应该阅读SQL注入 get_name()易受攻击。这里没什么大不了,因为数据来自其他查询,但仍然不要直接在查询字符串中使用参数。


Below is an edited version of my actual code:

<?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;


     }
}


?>

Then within a separate document i have an include for the file above. I call the function get name using the following:

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

get_name actually contains a calculation for calculating the distance between two points however because its a lengthy calculation i have left it out of the example above.

Its important that i can just use $obj->get_name() to get the output for $lat and $lng

解决方案

You're running into a scoping issue. The variables are only available to the function that declared them. To make them available, you can either pass the variables to the function explicitly (you need to make sure you always call get_coordinates() before display_coordinates() though, otherwise you'll have undefined values), or using global variables (bad idea).

The best method is probably to make a class for it (although it depends on how you intend to use it). Your variables will always be in scope, and you won't run the risk of trying to run the display_coordinates() function before you've initialized the variables.

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.

You should read up on Variable Scope and Classes and Objects to understand more about this.

To put this together with your original code, you would do something like this,

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 after question updated

There are a few bad practices in your code, but here's some quick steps to get what you want.

// 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 to your question, but you should also read about "SQL Injection" as query in get_name() is vulnerable. Not a big deal here, since the data comes from your other query anyway, but still good practice not to use parameters directly in a query string.

这篇关于在函数之间传递变量 - php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆