Heim  >  Artikel  >  Backend-Entwicklung  >  PHP被包含文件中变量共享问题

PHP被包含文件中变量共享问题

WBOY
WBOYOriginal
2016-06-06 20:22:521370Durchsuche

自学PHP过程中遇到一些问题,可能问题会有常识性的错误,请各位见谅!谢谢!
如题,有以下测试用例
a.php

<code><?php $msg = 'hello';
    
    include 'b.php';
?></code>

b.php

<code><?php echo $msg; // 输出 hello
?></code>

但是这样的话, 在Zend Studio中会有Undefined variable '$msg'的警告,虽然不影响运行结果,但是对于后期维护或者其他人的阅读会有影响,所以我想问问这有什么好的方法可以解决这种"强迫症"问题?可以让Zend Studio不报这个警告?


typecho源码过程中看到如下语句,位于
/usr/themes/default/404.php

<code><?php if (!defined('__TYPECHO_ROOT_DIR__')) exit; ?>
<?php $this->need('header.php'); ?>

    <div class="col-mb-12 col-tb-8 col-tb-offset-2">
        <div class="error-page">
            <h2 class="post-title">404 - <?php _e('页面没找到'); ?>
</h2>
            <p><?php _e('你想查看的页面已被转移或删除了, 要不要搜索看看: '); ?></p>
            <form method="post">
                <p><input type="text" name="s" class="text" autofocus></p>
                <p><button type="submit" class="submit"><?php _e('搜索'); ?></button></p>
            </form>
        </div>

    </div>
<!-- end #content-->
    <?php $this->need('footer.php'); ?></code>

typecho是如何实现使用$this访问need的呢?
我注意到typecho的主题模板中都是使用的$this来使用提供的插件或者功能的,这又是什么原理呢?

回复内容:

自学PHP过程中遇到一些问题,可能问题会有常识性的错误,请各位见谅!谢谢!
如题,有以下测试用例
a.php

<code><?php $msg = 'hello';
    
    include 'b.php';
?></code>

b.php

<code><?php echo $msg; // 输出 hello
?></code>

但是这样的话, 在Zend Studio中会有Undefined variable '$msg'的警告,虽然不影响运行结果,但是对于后期维护或者其他人的阅读会有影响,所以我想问问这有什么好的方法可以解决这种"强迫症"问题?可以让Zend Studio不报这个警告?


typecho源码过程中看到如下语句,位于
/usr/themes/default/404.php

<code><?php if (!defined('__TYPECHO_ROOT_DIR__')) exit; ?>
<?php $this->need('header.php'); ?>

    <div class="col-mb-12 col-tb-8 col-tb-offset-2">
        <div class="error-page">
            <h2 class="post-title">404 - <?php _e('页面没找到'); ?>
</h2>
            <p><?php _e('你想查看的页面已被转移或删除了, 要不要搜索看看: '); ?></p>
            <form method="post">
                <p><input type="text" name="s" class="text" autofocus></p>
                <p><button type="submit" class="submit"><?php _e('搜索'); ?></button></p>
            </form>
        </div>

    </div>
<!-- end #content-->
    <?php $this->need('footer.php'); ?></code>

typecho是如何实现使用$this访问need的呢?
我注意到typecho的主题模板中都是使用的$this来使用提供的插件或者功能的,这又是什么原理呢?

  1. 不要使用裸的全局变量,把它包装到某个class里面。

  2. 模板是被某个对象的方法include的,其作用域内有$this这个变量。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP7 错误处理Nächster Artikel:如何限定网站付费信息显示时间