Jean-Loup
Jean-Loup

Reputation: 340

Run PHP function from parent file

I need some help for a problem i'm facing. I've look on the web but i only found more usual issues which cannot solve mine.

The main idea is to run PHP functions like get_included_files(), get_defined_vars(), debug_backtrace() from the parent file.

In my code i have a PHP file, let's call it A.php which is including another PHP file, let's say B.php. I would like to run for exemple get_included_files() into B.php to get the files included in A.php.

Something similar to parent:: but for PHP files and not oriented object programming. I'm aware that it could be a security flaw, that's why i'm not sure it is possible, but i ask to be sure.

To be the clearest possible, here is an example :

A.php

include 'B.php';
include 'C.php';
include 'D.php';

get_includes();

B.php

function get_includes()
{
    $included_files = get_included_files();
    print_r($included_files);
}

And i need the $included_files var to contain array('B','C','D'). My problem is the PHP functions getting the included files from the file it's launched in, not from the parent (with this code, the $included_files is empty).

Upvotes: 0

Views: 311

Answers (3)

Saahon
Saahon

Reputation: 419

php is an interpreter, and interpretation will be strings. So the file a.php try to include files in the following order:

include 'С.php';
include 'D.php';
include 'B.php';

Upvotes: 1

fbastien
fbastien

Reputation: 800

I don't know if it would solve your problem, but you can also execute these function in the parent file, assign the result to a variable, and read this variable in included files.

For instance:

A.php

$a = 1;

$files = get_included_files();
$vars = get_defined_vars();

include 'B.php';

$b = 2;

$files = get_included_files();
$vars = get_defined_vars();

include 'C.php';

B.php

echo 'B<br /><pre>';
print_r($files);
print_r($vars);
echo '</pre>';

C.php

echo '<br />C<br /><pre>';
print_r($files);
print_r($vars);
echo '</pre>';

It will give an output that looks like this:

B

Array
(
    [0] => A.php
)
Array
(
    [...]
    [a] => 1
    [files] => Array
        (
            [0] => A.php
        )
)


C

Array
(
    [0] => A.php
    [1] => B.php
)
Array
(
    [a] => 1
    [files] => Array
        (
            [0] => A.php
            [1] => B.php
        )
    [vars] => Array
        [...]
    [b] => 2
)

Note that you can't get info about files and vars that are included/defined after the call to the function, so anyway from B.php you can't know that C.php and D.php will be included later.

Upvotes: 0

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

Consider the example:

a.php

function a(){
    echo "a";
}

function b(){
    echo "b";
}

b.php

include "a.php";

echo a();//echoes a

echo b();//echoes b

Upvotes: 0

Related Questions