简体   繁体   中英

Is it possible to include file in an include file in PHP

I have a basic page structure in php that contains include files for head and footer. In the footer, i want to add an include file that will load only if the page as the data-table class. Something like:

if ($class == 'data-table')
    include(SHARED_PATH . '/load-datatables.php');

My goal is to load scripts only when needed. I'm a newby in PHP so I want to start with simple things. Thanks!

If you are going to search for the "data-table" class in the page using php that would be hard. Although here's what you can do.

Add a php variable that indicates whether the datatable class "data-table" is being used in the page

// index.php

<?php $pageUsesDataTable = true; ?>
...
...
<table class="data-table">.....</table>

// Then load the script if depending on the variable

if ($pageUsesDataTable)
    include(SHARED_PATH . '/load-datatables.php');

Or you could just check if the "data-table" class exists in the page, if so initialize the datatable if it is generic

// dTable.js or <script>

if($('.data-table').length != 0) {
  // initialize the datatable
}

Although there's always a cleaner approach out there, try to search deeper. Good luck

Put this variable in those pages where you want to include the php-file load-datatables:

$include_datatables_file = true;

Then include a generic file called checkinclude.php on all your pages: checkinclude.php:

if (!isset($include_datatable_file)) {$include_datatable_file = false;}
if ($include_datatable_file === true) {
    include_once(SHARED_PATH . '/load-datatables.php');
}

After Anurag's comment: Did you try it... Of course I did, but I didn't get the right path so it didn't work. Changed the path and it works as expected. Like I said, it might not be the cleanest way or the best practice. But it works and it's easy to set up. Thanks for all answers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM