2017-07-26 177 views
0

我對PHP相當陌生,現在仍在學習如何使用某些include/require函數。我正在研究一個插件,並且我正在嘗試將主模板分解成幾個文件,以便更易於閱讀/維護(如果這是一個糟糕的主意,那麼這是一個其他的討論)。我的插件公用文件夾看起來有點像這樣:當我在相對路徑中包含目錄時,爲什麼我的PHP包含語句失敗?

resources-plugin 
    ├── includes 
    │ ├── class-resources-short-codes.php 
    │ └── index.php 
    ├── index.php 
    ├── public 
    │ └── partials 
    │  ├── resources-banner.php 
    │  ├── resources-filters.php 
    │  ├── resources-items.php 
    │  └── resources-query.php 

在我類資源 - 短codes.php文件,我有三個工作包括聲明:

add_shortcode('example-resources-sc', function() { 

    // Banner 
    include(dirname(__FILE__) . "/../public/partials/resources-banner.php"); 

    echo "<article class='resources flex-container'>"; 

    // Filters 
    include(dirname(__FILE__) . "/../public/partials/resources-filters.php"); 

    // Resources 
    include(dirname(__FILE__) . "/../public/partials/resources-items.php"); 

    echo "</article><!-- /resources -->"; 

}); 

然後,在子模板資源-filters.php,我還有一個包括應該在HTML拉從資源,query.php文件:

<?php 

// Doesn't work 
// include("./resources-query.php"); 
// include(plugins_url("resources-plugin/public/partials/resources-query.php")); 

// Works 
//include("resources-query.php"); 
include(dirname(__FILE__)) . "/resources-query.php"; 

?> 

<div class="slide-container">Other HTML here.</div> 

我的問題是 - 爲什麼這些方法中的兩個有效,但其他兩個不行?我知道我對使用嵌套包含語句時如何確定文件路徑有點困惑。

PHP版本:5.3.3 WordPress版本:4.2.2

謝謝!

+0

用'/'開始路徑意味着從根開始。 – j08691

+1

我不知道最後一個例子如何工作。圓括號是錯誤的。更改: 'include(dirname(__FILE__))。 「/資源的查詢。php「;' : 'include(dirname(__FILE__)。」/resources-query.php「);' – manassehkatz

+0

@manassehkatz這絕對是我的代碼中的一個錯字,所以我不知道爲什麼它作品,但它的顯示。 – kauffee000

回答

3

首先,我建議只在腳本的頂部使用dirname(),如果需要的話。如果你的wp-config.php文件看,你會看到,他們做這樣的周圍線80類似的東西:

define('ABSPATH', dirname(__FILE__) . '/'); 

在你的情況,你可以做這樣的事情:

define('MYPATH', dirname(__FILE__)); 


add_shortcode('example-resources-sc', function() { 

    // Banner 
    include(MYPATH . "/../public/partials/resources-banner.php"); 

    echo "<article class='resources flex-container'>"; 

    // Filters 
    include(MYPATH . "/../public/partials/resources-filters.php"); 

    // Resources 
    include(MYPATH . "/../public/partials/resources-items.php"); 

    echo "</article><!-- /resources -->"; 

}); 

我們這些問題你問:

include("./resources-query.php"); 

這並不因爲默認工作PHP會以爲你是在目錄奇怪的PHP將允許你引用文件在同一目錄下,如果你刪除。,但儘量避免這種行爲,因爲它只是令人困惑的一般。

include(plugins_url("resources-plugin/public/partials/resources-query.php")); 

您給出的第二個示例的問題是您嘗試包含的URL不是路徑。有些系統允許這樣做,但默認情況下大多數不這樣做。

作爲一個規則,我會建議總是包括使用絕對文件名的文件,就像你在工作的例子中做的那樣。也許考慮像我提到的那樣定義一個常量,這應該有助於確保你總是指向正確的路徑。如果您需要一些錯誤反饋來解釋,請考慮使用require_once而不是include進行測試。最後考慮避免使用包含/../的路徑,因爲它們最終會讓你頭痛。

Koda

+0

這工作,並有很大的意義。「這是行不通的,因爲默認PHP贏得假設你所在的目錄。「我也不知道,謝謝! – kauffee000