dongshi1914
2012-10-17 14:01
浏览 42
已采纳

函数的变量不在函数外部显示

I am having trouble getting the value of a variable which is in a function outside the function...

Example:

function myfunction() {
    $name = 'myname';
    echo $name;
}

Then I call it...

if (something) {
    myfunction();
}

This is echoing $name, but if I try to echo $name inside the input value it won't show:

<input type="text" name="name" value="<?php echo $name ?>"

How can I get access to this variable value?

图片转代码服务由CSDN问答提供 功能建议

我无法获取函数外函数中变量的值...

示例:

  function myfunction(){
 $ name ='myname'; 
 echo $ name; 
} 
 <  / code>  
 
 

然后我称之为...

  if(something){
 myfunction(); 
} \  n   
 
 

这是回显 $ name ,但如果我尝试在输入值内回显 $ name 显示:

 &lt; input type =“text”name =“name”value =“&lt;?php echo $ name?&gt;”
   
 
 

如何访问此变量值?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douxie3625 2012-10-17 14:03
    已采纳

    The $name variable is local until you explicitly define it as global:

    function myfunction() {
        global $name;
        $name = 'myname';
        echo $name;
    }
    

    But this doesn't seem like a good use of globals here. Did you mean to return the value and assign it? (Or just use it once?)

    function myfunction() {
        $name = 'myname';
        return $name;
    }
    
    ...
    $name = myfunction();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqhgjay5753 2012-10-17 14:03

    Read abour variable scope The variable has local scope. You have to made it global. But better, use some template engine or implement Registry

    评论
    解决 无用
    打赏 举报
  • doumouyi4039 2012-10-17 14:04

    Its a matter of scope..

    http://php.net/manual/en/language.variables.scope.php

    Just as when you're in a closed room, we cant see what you do, but if you open a door, or put in a video camera people can, or can see limited things, or hear limited things.. this is how stuff works in computers too

    评论
    解决 无用
    打赏 举报
  • doulan8054 2012-10-17 14:04

    You should read the php page about scope.

    To do what you want there are two solutions:

    1. Make $name global, or
    2. return the variable from the function
    评论
    解决 无用
    打赏 举报
  • du2986 2012-10-17 14:06

    The $name variable is local in that function. So it's accessible only inside that function. If you want it to be accesible everywhere you can do the following:

    • declare it outside the function and inside the function type: global $name;
    • still declare it outside but pass her as a function argument by reference:

      function myFunc(&$name) { $name = "text"; }

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题