小编zan*_*win的帖子

给PHP包含()'d文件父变量范围

是否有一个包含文件在父范围内用于它所调用的文件?以下示例已简化,但执行相同的工作.

本质上,函数将包含一个文件,但是希望包含文件的范围是调用包含它的函数的范围.

main.php:

<?php
  if(!function_exists('myPlugin'))
  {
    function myPlugin($file)
      {
        if(file_exists($file)
        {
          require $file;
          return true;
        }
        return false;
      }
  }

  $myVar = 'something bar foo';

  $success = myPlugin('included.php');

  if($success)
  {
    echo $myResult;
  }
Run Code Online (Sandbox Code Playgroud)

included.php:

<?php
  $myResult = strlen($myVar);
Run Code Online (Sandbox Code Playgroud)

先谢谢,
亚历山大.

编辑:解决方案

嗯,有点,谢谢Chacha102的贡献.
现在也可以从课堂内调用!

main.php

<?php
  class front_controller extends controller
  {
    public function index_page()
    {
      $myVar = 'hello!';

      // This is the bit that makes it work.
      // I know, wrapping it in an extract() is ugly,
      // and the amount …
Run Code Online (Sandbox Code Playgroud)

php scope function include

9
推荐指数
1
解决办法
6395
查看次数

标签 统计

function ×1

include ×1

php ×1

scope ×1