在函数之间传递变量 - php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19016696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:39:53  来源:igfitidea点击:

Passing variable between functions - php

phpfunctionvariables

提问by andrew anderson

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:

然后在一个单独的文档中,我有一个包含上述文件的内容。我使用以下命令调用函数 get name:

<?=$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.

get_name 实际上包含一个计算两点之间的距离的计算,但是因为它是一个冗长的计算,我把它排除在上面的例子之外。

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

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

回答by Nicole

Functions operate within function scope, so the variables that you've set in get_coordinates()are local variables. To create global variables, you can use the global keyword:

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

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

Or $GLOBALSarray:

$GLOBALS数组:

<?php

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

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

get_coordinates();
display_coordinates();

However, this may not be the best way to set/access these variables because any function can change their state at any time, and you must call one function to set them before calling the other to display them. If you can describe your specific goal, you might be able to get better advice.

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

One betterway to accomplish this is to use a class, and pass the object where you need it (this simple example does not demonstrate proper encapsulation, but is a good starting point):

实现此目的的一种更好方法是使用一个类,并将对象传递到您需要的地方(这个简单的示例没有演示正确的封装,但它是一个很好的起点):

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

Another way that is commonly used in PHP is to pass things in associative arrays (arrays with strings for indexes). I don't prefer this usually, because the array does not declare what it intends to hold, but it is an option:

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

回答by Rich Adams

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).

您遇到了范围界定问题。变量只对声明它们的函数可用。为了使它们可用,您可以将变量显式传递给函数(您需要确保始终调用get_coordinates()之前display_coordinates(),否则您将获得未定义的值),或者使用全局变量(坏主意)。

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.

最好的方法可能是为它创建一个类(尽管这取决于您打算如何使用它)。您的变量将始终在范围内,并且您不会冒着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.

You should read up on Variable Scopeand Classes and Objectsto understand more about this.

您应该阅读Variable ScopeClasses and Objects以了解更多相关信息。

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.

与您的问题无关,但您还应该阅读“SQL 注入”,因为查询get_name()很容易受到攻击。这里没什么大不了的,因为数据无论如何都来自您的其他查询,但仍然是不直接在查询字符串中使用参数的好习惯。

回答by Ryan

One way of doing it:

一种方法:

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

回答by samjco

What about Session? https://www.php.net/manual/en/reserved.variables.session.php

会话呢? https://www.php.net/manual/en/reserved.variables.session.php

Creating New Session

创建新会话

session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;

Getting Session

获取会话

session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/

$_SESSION["newsession"]=$value;
/*session created*/

echo $_SESSION["newsession"];
/*session was getting*/

Updating Session

更新会话

session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/

$_SESSION["newsession"]=$value;
/*it is my new session*/

$_SESSION["newsession"]=$updatedvalue;
/*session updated*/

Deleting Session

删除会话

session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/

$_SESSION["newsession"]=$value;

unset($_SESSION["newsession"]);
/*session deleted. if you try using this you've got an error*/

回答by Mr. Polywhirl

Create a Coordinate.class.phpfile:

创建一个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();
?>

回答by Zak

Change of another post.. I think the better way:

更改另一篇文章.. 我认为更好的方法是:

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