简体   繁体   中英

combine / include various PHP files into one single PHP file

Hello Friends I am a newbie programmer and very very new to PHP. I am seeking help in writing a small php Function. The situation is like this:

I am running Joomla and I have a template which is in BLOCKS for example:

header.php
topmodules.php
mainbody.php
bottommodules.php
footer.php

All my blocks are placed in a directory (/layouts/blocks). All these blocks need to be joined in the main Index.php file.

The function I know is something like this:

<?php
function get_header(){
  require_once(TEMPLATEPATH.'/layouts/blocks/header.php');
}
?>

And then call it like:

<?php get_header(); ?>

But that is not very professional and also I will have to write a function for every file moreover this can also be accomplished by just using

<?php require(YOURBASEPATH . DS .'layouts'. DS .'blocks'. DS . "header.php"); ?>

But what I am looking for is to have a single function /class which can get that PHP file from that directory, just by passing the name of the file so that I can add some more blocks to that directory in future without re-writing the function and simply call them like:

<?php $this->getBlock('header') ?>
<?php $this->getBlock('topmodules') ?>
<?php $this->getBlock('mainbody') ?>
<?php $this->getBlock('bottommodules') ?>
<?php $this->getBlock('footer') ?>

Kindly help.

You just need to add a parameter to the function you have:

function getBlock($filename){
  require_once(YOURBASEPATH . DS . 'layouts' .DS . 'blocks'. DS . $filename .'.php');
}
function get_header_improved($s){
  require_once(TEMPLATEPATH.'/layouts/blocks/' . $s . '.php');
}

<?php get_header_improved('header') ?>
<?php get_header_improved('topmodules') ?>
<?php get_header_improved('mainbody') ?>
<?php get_header_improved('bottommodules') ?>
<?php get_header_improved('footer') ?>

I not tried, but this should work.

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