在PHP中将变量传递给它的父函数

在PHP中将变量传递给它的父函数

本文介绍了在PHP中将变量传递给它的父函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数中有一个函数,我需要内部函数使它的变量在父函数的作用域中可用,例如:

  function sayMyName(){
getName(); //内部函数生成$ name值

echo $ name; //使用$ name
}

sayMyName();

我可以在两个函数中轻松地全局化事物...但是我的情况要复杂得多并处理更多的变量和全球化每一个是有点乏味。



谢谢。



PS
i注意到很多回归的建议。对不起,我不清楚,我需要返回更多的变量..不是一个简单的回报。谢谢你们

解决方案

您可以使用 $ _ GLOBALS 不好的做法。所以,




1:使用:

 <?php 
function getName(){
$ name ='Smith';

返回$ name;
}

函数sayMyName(){
$ name = getName();

echo $ name;
}

sayMyName();
?>

显示:

  Smith 






2:使用:

 <?php 
function getName & $ name){
$ name ='Smith';
}

函数sayMyName(){
getName($ name);

echo $ name;
}

sayMyName();
?>

显示:

  Smith 






3:返回一起使用使用语句和引用

 <?php 
function sayMyName(){
$ surname = $ name ='Unknown';

$ temp = function()使用(& $ name,& $ surname){
$ surname ='Smith';
$ name ='John';
};

$ temp();

echo $ name,'',$ surname;
}

sayMyName();
?>

显示:

  John Smith 


I have a function w/in a function, and I need the inner function to make it's variables available in a scope of parent function, e.g.:

function sayMyName(){
    getName(); // inner function generates $name value

    echo $name; // use $name
}

sayMyName();

I could easily just globalize things w/in both functions... But my situation is far more complicated and handles more variables and globalizing each one is a bit tedious.

Thanks.

PSi noticed a lot of "return" suggestions. sorry i wasnt clear , i need to return more variables.. not a simple return. thanks guys

解决方案

You may use $_GLOBALS, but it`s a "bad practice". So,


1: Use return:

<?php
function getName(){
    $name = 'Smith';

    return $name;
}

function sayMyName(){
    $name = getName();

    echo $name;
}

sayMyName();
?>

Shows:

Smith


2: Use references:

<?php
function getName(&$name){
    $name = 'Smith';
}

function sayMyName(){
    getName($name);

    echo $name;
}

sayMyName();
?>

Shows:

Smith


3: Return array for multiple variables:

<?php
function getName(){
    $surname = 'Smith';
    $name    = 'John';

    return array($surname, $name);
}

function sayMyName(){
    list($surname, $name) = getName();

    echo $name, ' ', $surname;
}

sayMyName();
?>

Shows:

John Smith


4. Return custom object for multiple variables:

<?php
function getName(){
    $surname = 'Smith';
    $name    = 'John';

    $buffer = new stdClass();

    $buffer->name    = $name;
    $buffer->surname = $surname;

    return $buffer;
}

function sayMyName(){
    $obj = getName();

    echo $obj->name, ' ', $obj->surname;
}

sayMyName();
?>

Shows:

John Smith


5. Use anonymous function with use statement and references:

<?php
function sayMyName(){
    $surname = $name = 'Unknown';

    $temp = function() use (&$name, &$surname){
        $surname = 'Smith';
        $name    = 'John';
    };

    $temp();

    echo $name, ' ', $surname;
}

sayMyName();
?>

Shows:

John Smith

这篇关于在PHP中将变量传递给它的父函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 10:15