【问题标题】:variable scope in different files不同文件中的变量范围
【发布时间】:2014-01-18 00:44:32
【问题描述】:

我正在尝试在同一文件所需的另一个文件中使用在文件 f1 中声明的变量。

f1中的代码:

<?php

class Index extends Controller
{
    function __construct()
    {   
        parent::__construct();
    }

    public function index( $err = "" )
    {
        $err = "teeste";

        $this->view->render('index');
    }
}
?>

$this-&gt;view-&gt;render('index'); 行是正确的,我确定因为表单显示正确。

另一个文件的代码:

<form action='<?php echo URL . 'user';?>' method="POST">
<input type="text" name="login" maxlength="35"/>
<input type="password" name="pass" maxlength="35"/>
<input type="submit" value="Entrar">
</form>

<?php 
echo $err; 
?>

我在网上看到了很多这样的例子,但是这个即使很简单也行不通。

【问题讨论】:

  • 变量有函数作用域,文件无关。
  • 正如@Barmar 所说,文件在这里无关紧要。问题是$err 仅存在于index(..) 函数的范围内,因此无论您尝试在哪个文件中执行,都无法在该函数之外访问它。
  • 我已经尝试使 $err 成为对象的公共属性,但它仍然无法正常工作。

标签: php scope require


【解决方案1】:

谢谢大家。

我就是这样解决的。

<?php

class Index extends Controller
{
    public $err;

    function __construct()
    {   
        parent::__construct();
    }

    public function index()
    {
        $this->view->error = "teeste";

        $this->view->render('index');
    }
}
?>

<form action='<?php echo URL . 'user';?>' method="POST">
<input type="text" name="login" maxlength="35"/>
<input type="password" name="pass" maxlength="35"/>
<input type="submit" value="Entrar">
</form>

<?php 
echo $this->error; 
?>

【讨论】:

    【解决方案2】:

    您需要使用全局变量。在函数中:

    public function index($err = "") {
        global $global_err;
    
        $global_err = "teeste";
        $this->view->render('index');
    }
    

    然后在你的另一个文件中:

    echo $global_err;
    

    【讨论】:

      【解决方案3】:

      这看起来很像 codeigniter,所以我将按照我的看法回答这个问题

      class Index extends Controller
      {
          function __construct()
      {   
          parent::__construct();
      }
      
      public function index( $err = "" )
      {
          $data['err'] = "testee";
      
          $this->view->render('index', $data);
      }
      }
      ?>
      

      第二个文件

      <form action='<?php echo URL . 'user';?>' method="POST">
      <input type="text" name="login" maxlength="35"/>
      <input type="password" name="pass" maxlength="35"/>
      <input type="submit" value="Entrar">
      </form>
      
      <?php 
      echo $err; 
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 1970-01-01
        • 1970-01-01
        • 2022-10-07
        相关资源
        最近更新 更多