plugin_dir_path(__ FILE__)和__DIR__之间的区别

时间:2017-11-07 04:37:47

标签: php wordpress

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

3 个答案:

答案 0 :(得分:4)

plugin_dir_url(__FILE__)此功能为您提供文件目录的网址

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

__FILE__这个神奇的常量会为你提供文件存在的文件路径

__DIR__这个神奇的常量会为你提供文件存在的目录路径

trailingslashit(__DIR__)此函数将返回目录的路径,并在目录路径后添加shash。

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

答案 1 :(得分:3)

  1. plugin_dir_path(__ FILE__)返回指向当前文件的服务器文件系统目录路径,即
  2. 行中的内容

    /家庭/网络/ your_site /可湿性粉剂内容/插件/你-插件/包括/

    这可用于加载PHP文件。

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

    1. plugins_url()返回当前WordPress安装的插件文件夹的网址,即
    2. 的内容

      <强> http://example.com/wp-content/plugins

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

      1. plugin_dir_url()的行为方式与plugins_url()非常相似。它还返回一个Web地址,但带有一个斜杠,即
      2. <强> http://example.com/wp-content/plugins/

        后两个对于加载图像,样式表,JS很有用。

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

答案 2 :(得分:1)

让我们追踪发生的事情:

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 <5.3(不需要),则可以简化为:

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方法。成为反叛者!