【问题标题】:Difference between plugin_dir_path(__FILE__) and __DIR__plugin_dir_path(__FILE__) 和 __DIR__ 之间的区别
【发布时间】:2017-11-07 04:37:46
【问题描述】:

尾部斜杠“/”只是这两者之间的区别吗?如果是这样,我可以使用trailingslashit(__DIR__)

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    plugin_dir_url(__FILE__)该函数为您提供文件目录的url

    plugin_dir_url(__DIR__)此功能为您提供url插件文件夹。

    __FILE__这个神奇的常数会给你文件所在文件的路径

    __DIR__ 这个神奇的常量将为您提供文件所在目录的路径

    trailingslashit(__DIR__)这个函数会返回目录的路径,并在目录的路径后面加上shash。

    plugin_dir_path(__FILE__)。会给你与trailingslashit(__DIR__) 相同的结果。我建议使用插件目录路径,因为它是一种 wordpress 方式。

    【讨论】:

    • 对不起,我是想输入plugin_dir_path
    • 是的,你可以同时使用,但在 wordpress 中你应该使用 plugin_dir_path
    【解决方案2】:

    让我们了解正在发生的事情:

    wordpress的功能就这么简单:

    function plugin_dir_path( $file ) {
        return trailingslashit( dirname( $file ) );
    }
    

    所以,

    include plugin_dir_path(__FILE__) . 'xx.php';
    

    等于

    include trailingslashit( dirname( __FILE__ ) ) . 'xx.php';
    

    在 PHP 5.3 中,__DIR__ 被引入以替代 dirname( __FILE__ )。 如果你不需要支持 PHP

    include trailingslashit( __DIR__ ) . 'xx.php';
    

    (另见:Is there any difference between __DIR__ and dirname(__FILE__) in PHP?

    由于__DIR__ 不会返回带有斜杠的内容,因此无需执行trailingslashit 的操作。所以我们可以进一步简化为:

    include __DIR__ . '/xx.php';
    

    因此,总而言之,以下几行都做了完全相同的事情(在 PHP >= 5.3 上):

    include plugin_dir_path(__FILE__) . 'xx.php';
    include trailingslashit( dirname( __FILE__ ) ) . 'xx.php';
    include trailingslashit( __DIR__ ) . 'xx.php';
    include __DIR__ . '/xx.php';
    

    哪个最好?我更喜欢最后一个。您不必输入那么多,它的噪音更小,而且您不必担心 plugin_dir_path 函数内部有什么魔力。这就是您通常在 PHP 中包含文件的方式。一些牧师可能会说你应该用 Wordpress 的方式来做。做一个叛逆者!

    【讨论】:

    • 您可以在您的主插件/主题文件中定义一个常量,使其具有__DIR__ 的值,并在其他地方重用该常量,因此您可以确保您的包含和要求始终与插件/主题根文件夹。这很有用,因为__DIR__ 将指向每个文件夹中的不同文件夹。如果您出于某种原因移动文件,可能会导致问题。我只是首先创建一个 const define( 'MYPLUGINNAME_BASEDIR', __DIR__ );,然后在任何地方重用它。我的 IDE (PHPStorm) 也可以正确解决这个问题,使 include / require 检查再次有用。
    【解决方案3】:
    1. plugin_dir_path( __FILE__ ) 返回指向当前文件的服务器文件系统目录路径,即类似于

    /home/www/your_site/wp-content/plugins/your-plugin/includes/

    这可用于加载 PHP 文件。

    更多信息:https://developer.wordpress.org/reference/functions/plugin_dir_path/

    1. plugins_url() 返回当前 WordPress 安装的插件文件夹的网址,即类似于

    http://example.com/wp-content/plugins

    更多信息:https://codex.wordpress.org/Function_Reference/plugins_url

    1. plugin_dir_url() 的行为方式与 plugins_url() 非常相似。它还返回一个网址,但带有一个斜杠,即类似于

    http://example.com/wp-content/plugins/

    后两者对于加载图片、样式表、JS 很有用。

    更多信息:https://codex.wordpress.org/Function_Reference/plugin_dir_url

    【讨论】:

      猜你喜欢
      • 2011-02-14
      • 2011-08-16
      • 1970-01-01
      • 2016-11-19
      • 2021-12-27
      • 2012-10-05
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多