PHP在函数外部传递变量,不带全局变量

PHP在函数外部传递变量,不带全局变量,php,function,Php,Function,假设我在php中有这样一个函数: <?php function hello() { $x = 2; } 约翰·康德(John Conde)是对的,但要向您展示代码,它将是正确的 <?php function hello() { $x = 2; return $x; } $var = hello(); echo $var; ?> 约翰·康德是对的,但要向你展示代码,那就是 <?php function hello() { $x = 2

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

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

约翰·康德(John Conde)是对的,但要向您展示代码,它将是正确的

<?php 

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

$var = hello();
echo $var;

?>

约翰·康德是对的,但要向你展示代码,那就是

<?php 

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

$var = hello();
echo $var;

?>

您只需返回数据即可:

function hello() {
   $x = 2;
   return $x;
}
无论你想在哪里使用它的结果

$x=hello();

您只需返回您的数据:

function hello() {
   $x = 2;
   return $x;
}
无论你想在哪里使用它的结果

$x=hello();
以此为例:

<?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'
举个例子:

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

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

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

您只需返回函数外部的值:

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

$x = hello();

您可以在

中找到有关
列表()的更多信息。您只需在函数外部返回值:

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

$x = hello();

您可以在

中找到有关
列表()
的更多信息,只需从函数中返回变量即可。@johncode因此,以上面的示例为例,我是否需要在那里返回它?如果我有几个值呢?
返回$x
$x
可以是一个包含多个值的数组。只需从函数中返回变量即可。@johncode因此,以上面的示例为例,我是否需要在那里返回它?如果我有几个值呢?
返回$x
$x
可以是一个包含多个值的数组。@user3287771很乐意help@user3287771很乐意帮忙