Include PHP file with parameter - php

newbie in PHP here, sorry for troubling you.
I want to ask something, if I want to include a php page, can I use parameter to define the page which I'll be calling?
Let's say I have to include a title part in my template page. Every page has different title which will be represented as an image. So,
is it possible for me to call something <?php #include('title.php',<image title>); ?> inside my template.php?
so the include will return title page with specific image to represent the title.
thank you guys.

An included page will see all the variables for the current scope.
$title = 'image title';
include('title.php');
Then in your title.php file that variable is there.
echo '<h1>'.$title.'</h1>';
It's recommended to check if the variable isset() before using it. Like this.
if(isset($title))
{
echo '<h1>'.$title.'</h1>';
}
else
{
// handle an error
}
EDIT:
Alternatively, if you want to use a function call approach. It's best to make the function specific to activity being performed by the included file.
function do_title($title)
{
include('title.php'); // note: $title will be a local variable
}

Not sure if this is what you're looking for, but you can create a function to include the file and pass a variable.
function includeFile($file, $param) {
echo $param;
include_once($file);
}
includeFile('title.php', "title");

In your included file, you could do this:
<?php
return function($title) {
do_title_things($title);
do_other_things();
};
function do_title_things($title) {
// ...
}
function do_other_things() {
// ...
}
Then, you could pass the parameter as such:
$callback = include('myfile.php');
$callback('new title');
Another more commonly used pattern is to make a new scope for variables to be passed in:
function include_with_vars($file, $params) {
extract($params);
include($file);
}
include_with_vars('myfile.php', array(
'title' => 'my title'
));

The included page will already have access to those variables defined prior to the include. If you require include specific variables, I suggest defining those variables on the page to be included

Related

require_once the same file multiple time?

I have a config file that contain credential information to connect to an API
I include my config file in 2 functions in 2 different file
In the first called function, I have my credential variables but when I call my second function, my credential variables are empty.
index.php
<?php
require_once("./connector/hot/hotelbeds/book.php");
if($_REQUEST['connector'] == 'hotelbeds')
{
require_once("connector/hot/hotelbeds/validate.php");
validate_hotelbeds($_REQUEST);
}
$booking_output = book_hotelbeds($_REQUEST);
?>
validate.php
<?php
function validate_hotelbeds($results)
{
$account = $results['header']['account'];
include_once("./connector/hot/hotelbeds/account_config/$account/config.php");
// $url contain my url
$validate = curl_get($url , $results);
}
?>
book.php
<?php
function book_hotelbeds($results)
{
$account = $results['header']['account'];
include_once("./connector/hot/hotelbeds/account_config/$account/config.php");
// $url is empty
$book = curl_get($url , $results);
}
?>
config.php
<?php
$url = "http://www.websitelink.com";
?>
The first time you require it, the variables will be introduced.
When you require it again from inside a function, the file has already been required so it is ignored.
The variables are outside the scope of the function at this point, so if you have to you would need to access them by declaring them as global.
Perhaps a better idea would be do declare those variables as constants instead, which means they will be available within the function scopes:
$myVariable = 'hello';
define('MY_CONSTANT', 'world');
echo 'Global scope: ', $myVariable, MY_CONSTANT, PHP_EOL; // helloworld
function myFunction()
{
echo 'Function scope: ', $myVariable, MY_CONSTANT, PHP_EOL; // world
}
function myGlobalFunction()
{
global $myVariable;
echo 'Function scope using global: ', $myVariable, MY_CONSTANT, PHP_EOL; // helloworld
}
Example.
Put your include_once("./connector/hot/hotelbeds/account_config/$account/config.php"); into index instead. Then if you wanted to use the var $url you would need a line above stating that you want that global var: global $url;.
Also I suggest changing $url name and change it to constant like: const API_URL = 'website_url'
Functions require_once and include_once include file only on time for one call of script. Because you include files book.php and validate.php in index.php then PHP include config.php only one time.
You can include config.php in index.php and use global directive inside your function.
Or you can just use functions include and require. These functions include one file to script many times - on each call.

PHP: how to check if a given file has been included() inside a function

I have a PHP file that can be include'd() in various places inside another page. I want to know whether it has been included inside a function. How can I do this? Thanks.
There's a function called debug_backtrace() that will return the current call stack as an array. It feels like a somewhat ugly solution but it'll probably work for most cases:
$allowedFunctions = array('include', 'include_once', 'require', 'require_once');
foreach (debug_backtrace() as $call) {
// ignore calls to include/require
if (isset($call['function']) && !in_array($call['function'], $allowedFunctions)) {
echo 'File has not been included in the top scope.';
exit;
}
}
You can set a variable in the included file and check for that variable in your functions:
include.php:
$included = true;
anotherfile.php:
function whatever() {
global $included;
if (isset($included)) {
// It has been included.
}
}
whatever();
You can check if the file is in the array returned by get_included_files(). (Note that list elements are full pathnames.) To see if inclusion occurred during a particular function call, check get_included_files before and after the function call.

Undefined variable after wrapped include in PHP

I'm using PHP for web development. I'm using the following function to wrap the include of a view:
<?php
function render($templateFile) {
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}
?>
Although this seems right to me, there is a really unexpected behavior: when I define a variable to something (e.g. an array) and use render for including a view that uses that variable, I get an undefined variable error. But when I explicitely use include there is no error at all and things are just fine.
This is the script that calls render:
<?php
include 'lib/render.php'; // Includes the function above.
$names = array('Trevor', 'Michael', 'Franklin');
render('names.html'); // Error, but "include 'views/names.html'" works fine.
?>
And this is the file that uses the $names variable:
<html>
<head>
<title>Names</title>
</head>
<body>
<ol>
<?php foreach ($names as $name): ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
Help will be very much appreciated.
This is from the PHP documentation on the include function (c.f. http://us1.php.net/manual/en/function.include.php):
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
And also:
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function. So, it will follow the variable
scope of that function.
So, if your render function can't access $names, then neither can your included file.
A possible solution would be to pass the parameters you want to be able to access in your view template, to your render function. So, something like this:
function render($templateFile, $params=array()) {
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}
Then, pass them like this:
$names = array('Trevor', 'Michael', 'Franklin');
render('names.html', array("names" => $names));
And use them in your view template like this:
<html>
<head>
<title>Names</title>
</head>
<body>
<ol>
<?php foreach ($params['names'] as $name): ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
There are probably better solutions to this, like putting your render function into a View class. Then you can call the View class function from inside your template file, and access parameters that way instead of just assuming there will be a $params variable in the view templates scope. But, this is the simplest solution.
The problem is, when you include the file directly using include 'views/names.html' the variable $name remains in the same files scope. Hence, it works. But when the include is done through the function, the varibale $name remains out of scope inside the function. So it doesn't work. For example, declare $names as global inside the function and it will work.
If you update the function like below you will see $names variable works.
function render($templateFile) {
global $names; // declares the global $names variable to use in the included files
$templateDir = 'views/';
if (file_exists($templateDir . $templateFile)) {
include $templateDir . $templateFile;
} else {
throw new Exception("Template '{$templateFile}' couldn't be found " .
"in '{$templateDir}'");
}
}

php how to access language variable inside a function when the language page has already been included?

My php script includes another en.php file which contains the required english strings. This same page also calls a html page which uses the file and formats it using the contents of the en.php file.
I have a function in this script which references variables defined in the included script but I am getting error messages of the variable not being found. If I reference the variable outside the function, the variable is accessed correctly. Why can I not access these variables inside the function?
en.php
<?php
$lang_yes = 'Yes';
$lang_no = 'No';
?>
example.php
<?php
include_once('addons/assq/lang/en.php');
echo $lang_yes;
$q1 = convertToYesOrNoString(0);
echo $q1;
function convertToYesOrNoString($value){
//include_once('addons/assq/lang/en.php');
if ($value == 0){
return $lang_no;
}else if ($value == 1){
return $lang_yes;
}else{
return "---";
}
}
?>
My output is as follows:
Yes
Undefined variable: lang_no in example.php on the line in the function
I tried including the en.php directly into the function but that did not work either. How can I access these variables inside my function while including the file as implemented above?
You can either define it as a constant, pass it as an argument or declare it as a global within the function:
function convertToYesOrNoString($value){
global $lang_no, $lang_yes;
//...
}
That's a scope issue. That variable $lang_no will not be accessed under that function , you need to pass that as a parameter instead to the function definition.
function convertToYesOrNoString($value,$lang_no){ //<--- Like this.
Since you have mentioned that you have a lot of parameters .. you can write a turnaround like this...
Your en.php
<?php
//Map all those variables inside an array as key-value pair. as shown
$varArray=array('lang_yes'=>'Yes','lang_no'=>'No');
Some test.php
<?php
include('en.php');
function convertToYesOrNoString($varArray)
{
extract($varArray);
echo $lang_yes; // "prints" Yes
echo $lang_no; // "prints" No
}
convertToYesOrNoString($varArray);

Calling a single function from another file without including the whole file in php

Is it possible to call only the specific function from another file without including whole file???
There may be another functions in the file and don't need to render other function.
The short answer is: no, you can't.
The long answers is: yes, if you use OOP.
Split your functions into different files. Say you are making a game with a hero:
Walk.php
function walk($distance,speed){
//walk code
}
Die.php
function die(){
//game over
}
Hero.php
include 'Walk.php';
include 'Die.php';
class Hero(){
//hero that can walk & can die
}
You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.
One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.
In PHP it's not available to get only a little part of a file.
Maybe this is a ability to use only little parts of a file:
I have a class that calls "utilities". This I am using in my projects.
In my index.php
include("class.utilities.php")
$utilities = new utilities();
The file class.utilities.php
class utilities {
function __construct() {
}
public function thisIsTheFunction($a,$b)
{
$c = $a + $b;
return $c;
}
}
And then i can use the function
echo $utilities->thisIsTheFunction(3,4);
include a page lets say the function is GetPage and the variable is ID
<?php
require('page.php');
$id = ($_GET['id']);
if($id != '') {
getpage($id);
}
?>
now when you make the function
<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>

Categories