PHP在函数之外传递变量而没有全局变量

时间:2014-02-19 22:09:30

标签: php function

假设我在php中有这样的函数:

<?php function hello() {
   $x = 2;
}

我想在不使用全局的情况下在该函数之外使用该变量,因为我听说这是一个坏主意,因为它的安全性问题。 (对吗?)。

无论如何,获得这个价值的最佳途径是什么?我可以通过使用“this”在java中执行此操作。但不确定它在PHP中是如何工作的。感谢。

更新

这是我需要帮助的代码:

<?php
require('includes/connect.php');

function connectHouseObjects() {

        global $mysqli;
        /* Register a prepared statement */
        if ($stmt = $mysqli->prepare('SELECT x FROM house_room1 WHERE user_id = ?')) {

                /* Bind parametres */
                $stmt->bind_param('i', $user_id);

                /* Insert the parameter values */
                $user_id = 1;

                /* Execute the query */
                $stmt->execute();

                /* Bind resultatet */
                $stmt->bind_result($x);

                while ($stmt->fetch()) {
                    //looping through the x's and y's
                }

                /* Close statement */
                $stmt->close();
        return $x;
            } else {
                /* Something went wrong */
                echo 'Something went terrible wrong'     . $mysqli->error;
            }
        }
?>

5 个答案:

答案 0 :(得分:5)

John Conde是对的,但要向您展示代码

<?php 

function hello() {
   $x = 2;
   return $x;
}

$var = hello();
echo $var;

?>

答案 1 :(得分:5)

您只需返回数据:

function hello() {
   $x = 2;
   return $x;
}

并在任何地方使用其结果;

$x=hello();

答案 2 :(得分:4)

以此为例:

<?php 

function hello(){
    $x=2;
    //this is where you get it out
    return $x;
}
//here we are outside the function
$x = hello();
//$x now equals 2;
?>

从函数返回变量允许您调用函数并将其分配到外部。

更加面向对象:

<?php

class Talk
{
    protected $message;

    public function setMessage($message){
        //this will set your class variable to what ever is in $message
        $this->message = $message;
    }
    public function getMessage()
    {
        //This will give you what ever your current message is
        return $this->message;
    }
}
//Then to use this you could do
$talk = new Talk();
//That sets up $talk to be an instance of the talk class

$talk->setMessage('Hello');
//This will then sets the message in talk to hello then to retrieve it just do

$message = $talk->getMessage();

//Now outside the class we have a variable $message that contains 'Hello'

答案 3 :(得分:0)

您也可以像在Java中一样创建一个类,并使用可以从该类中的其他函数访问的类变量。

答案 4 :(得分:0)

您只需将值返回到函数外部:

<?php
function hello() {
    $x = 2;
    return $x;
}

$x = hello();

如果要返回多个值,可以使用list()函数,同时将值作为数组返回:

<?php
function hello() {
    $x = 2;
    $y = 3;
    return array($x, $y);
}

list($x, $y) = hello();

您可以在 PHP manual

中找到有关list()的更多信息