I have one file called paths.php that has the following code :
<?php
$path_1="db";
$path_2="files";
?>
This file is included in other files, for example file index.php and the following include : include("paths.php");
In index.php, where I got this include, I also have the following function :
<?php
function explode($value,$separator)
{
/// Into I need take value $path_1 ///
$exp=explode("$separator","$value");
for ($i=0;$i<count($exp);$i++)
{
print "".$exp[$i]."";
}
}
?>
The problem is that I need to the read the value ($value) from the include inside the function scope. I have problems with the function, the include has to be in the function to work.
Is it possible that the function take these values and do not need the include to be inside the function, because if I don't put the include inside it doesn't take correct values?
I'm having a hard time understanding what you mean. But I noticed some problem in your code:
function explode($value,$separator)
{
explode() is a built-in PHP function. You cannot redeclare it. You need to use a different function name for your function.
If you wish to access $path_1 and $path_2 from inside a function you created, you need to use global. For example:
function custom_explode($value,$separator) {
global $path_1, $path_2;
// your other codes
echo 'I can now access $path_1: '.$path_1.' and $path_2: '.$path_2.'!';
}
Related
I currently have this PHP code;
private function generateSpecialPage(){
require_once("/view/pages/special.php");
}
Special.php is a php file mostly filled with html. I'm trying to obtain the name of the current function from inside special.php.
If I echo the magic constant FUNCTION before the require, it echoes "generateSpecialPage", which is what I want. However, if I echo FUNCTION from special.php, it echoes nothing.
I'm able to get the current class' name from inside special.php using get_class($this), I was wondering if there was an equally elegant solution for the current method.
You should probably re-organize your code to change require_once("/view/pages/special.php") into a separate function and pass in the function name.
If you call generateSpecialPage() a second time, it won't do anything. You could get around this by changing it to require(), but then you're loading the file every time which is unnecessary.
The required file lives in the same scope as the function that required it.
So you can simply store to a variable before requiring the file:
private function generateSpecialPage() {
$caller = __FUNCTION__;
require_once '/view/pages/special.php';
}
then in special.php you have a regular variable $caller:
<?= "required by {$caller}" ?>
A general purpose call stack inspector will let you look back to fetch the caller function, class or object, file, and line. The one I use as part of my framework looks like, in essence:
function caller($offset = 0) {
return (new \Exception)->getTrace()[1+$offset];
}
Using this in your special.php will yield the desired result:
<?php echo caller(1)['function']; ?>
The call stack at that point is special.php -> require -> doSomethingSpecial, so we use the 1 offset to skip passed the require and get the doSomethingSpecial frame.
However, you might consider refactoring your view to receive parameters, rather than taking environmental cues. A general purpose view loader would go something like this:
function render($template, array $params = []) {
extract($params);
require $template;
}
which would then have a template that looked liked:
<?php echo "Hello {$caller}" ?>
and could be called like:
private function doSomethingSpecial() {
render('special.php', [ 'caller' => __FUNCTION__ ]);
}
I realize this is more typing than might be desired, but it affords more flexibility in the long-term, as it decouples the view from the caller.
This question already has answers here:
Is it possible to overwrite a function in PHP
(10 answers)
Closed 9 years ago.
I have a main php file in the root which is included by several others on different directories ,I don't want to allow few functions written in main files to execute if included by another file.
I ran an test code and tried overwriting an function by re-declaring it on including but it returned an error:
a.php
<?php
function show(){echo "a";}//This is what I want to over-ride with
include 'b.php';
b.php
<?php
function show(){echo "b";}//This is the function i want to restrict.
show();
Fatal error: Cannot redeclare abc() (previously declared in C:\xampp\htdocs\abc.php:3) in C:\xampp\htdocs\xyz.php on line xx.
You can do this with anonymous functions (PHP5.3)
$show = function(){
echo "a";
};
$show = function(){
echo "b";
};
$show();
Will now echo "b".
You can't redeclare a function. You need to use unique names for each function.
The functions won't execute just because you include the file they're in. That is unless you're actively calling them inside the file.
I'd suggest evaluating the way you include files to resolve your issue. You may also want to look into include_once / require_once and the function_exists conditional.
E.g.
if ( ! function_exists( 'my_function' ) ) :
function my_function() {
}
endif;
The best way to do this would be to use PHP's OOP features, which allow you to specify visibility of methods.
You can check within a function if the "main file" is included or not, try something like this:
function someFunction() {
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
echo "Not included.";
} else {
echo "Included. No access.";
}
}
Or place the condition "outside" the function(s) definition, so it won't be defined if you include that file.
But I would go with an OOP approach.
In my code, I use a public load_snippet function of a class when I need to include HTML or PHP snippets. (I do this instead of a direct include_once because the directory structure varies depending on certain variables).
I had some issues with variable scopes, so I've narrowed down the problem to this: let's say I define a variable within my page:
$variable = 'Hello World!";
Then, I need load in a snippet:
$APP->load_snippet("slider");
The snippet renders perfectly, except that PHP gives an undefined variable error if I try to reference $variable in the slider code. If I directly include the php file, it works as expected, so I don't understand why I'm having this problem, since this is the load_snippet function:
public function load_snippet($snippet){
if(file_exists("app/".$this->APP_TYPE."/snippets/".$snippet.".php")){
include "app/".$this->APP_TYPE."/snippets/".$snippet.".php";
}
else{
include 'common/txt/404.txt';
}
}
Any help you can give me is much appreciated.
The file is being included within the context of the load_snippet() function, and therefore has only those variables which exist within that function. One way to modify this is to make your function accept two variables: the filename and an array of values.
public function load_snippet($snippet, $content) {
if (is_array($content)) extract($content);
if (file_exists("app/".$this->APP_TYPE."/snippets/".$snippet.".php")) {
include "app/".$this->APP_TYPE."/snippets/".$snippet.".php";
} else {
include 'common/txt/404.txt';
}
}
Then
$arr = array('variable' => 'Hello world!');
load_snippet('slider', $arr);
I think include inside a function makes no sense to me... I think that you should put in function
global $variable;
Note that include will put the code inside the function(include will be replaced by code) as i know..
The way you are doing it is an ugly one, but you can use global $variable inside the snipped to refer to the variable. However if you include the snipped inside a function or a method, you'll have to make the variables in that function/method global as well
If you need $variable inside of the App::load_snippet() method, it would probably be best to pass it in:
public function load_snippet($snippet, $var='Hello world'){
if(file_exists("app/".$this->APP_TYPE."/snippets/".$snippet.".php")){
include "app/".$this->APP_TYPE."/snippets/".$snippet.".php";
}else{
include 'common/txt/404.txt';
}
}
//do something with $var
}
You can set a default for when $variable hasn't been set. No globals, no out of scope variables.
Instead you can use the constants like define('VARIALABLE','value'). which will be available to you anywhere in your file
You are including inside a class. Which means that the included file has the same variable scope as the line of code which includes it has. TO fix this all you need to do is put
global $variable;
Above the include.
I'm having a bit of trouble understanding includes and function scopes in PHP, and a bit of Googling hasn't provided successful results. But here is the problem:
This does not work:
function include_a(){
// Just imagine some complicated code
if(isset($_SESSION['language'])){
include 'left_side2.php';
} else {
include 'left_side.php';
}
// More complicated code to determine which file to include
}
function b() {
include_a();
print_r($lang); // Will say that $lang is undefined
}
So essentially, there is an array called $lang in left_side.php and left_side2.php. I want to access it inside b(), but the code setup above will say that $lang is undefined. However, when I copy and paste the exact code in include_a() at the very beginning of b(), it will work fine. But as you can imagine, I do not wish to copy and paste the code in every function that I need it.
How can I alleviate this scope issue and what am I doing wrong?
If the array $lang gets defined inside the include_a() function, it is scoped to that function only, even if that function is called inside b(). To access $lang inside b() you need to call it globally.
This happens because you include 'left_side2.php'; inside the include_a() function. If there are several variables defined inside the includes and you want them to be at global scope, then you will need to define them as such.
Inside the left_side.php, define them as:
$GLOBALS['lang'] = whatever...;
Then in the function that calls them, try this:
function b() {
include_a();
print_r($GLOBALS['lang']); // Now $lang should be known.
}
It is considered 'bad practice' to use globals where you don't have to (not a consideration I subscribe to, but generally accepted). The better practice is to pass by reference by adding an ampersand in front of the passed variable so you can edit the value.
So inside left_side or left_side2 you would have:
b($lang);
and b would be:
function b(&$lang){...}
For further definitions on variable scopes check this out
hello i want to know how to call a function defined in one php file from some other function defined in some other php page.
do like this, in the file where you need to call the function
require_once("file_having_function_that_you_need_to_call.php");
function_name($arguments); // this function is defined in 'file_having_function_that_you_need_to_call.php' file
First you need to include that file either using
require_once or require
or
include_once or include
if the function is not in class, you will call directly.
require("file.php");
echo getUserName("1")
otherwise you have to first create object and than call method
require("file.php");
$obj = new User();
echo $obj->getUserName("1");
Use include(), require(), etc. on the other PHP file, then just put the function name followed by its arguments in parentheses.