6

Is it possible to include (or, for my uses, run) another PHP file from within a PHP script without inheriting the variables set in the parent script? I know this is mostly possible to do by wrapping the include in a function, but that feels sloppy.

Is there a more elegant alternative?

5
  • 1
    The include will inherit whatever's in scope where included, so wrapping it in a function really is the solution. The other solution is to limit the number of globals you're creating in the parent script. If they ought not be exposed in various includes, then perhaps they shouldn't be global to begin with. Commented Jul 13, 2012 at 16:28
  • I don't actually have any set globals, so wrapping it in a function WILL solve the problem. I was just hoping there's a more specific function for it, or something. :) Commented Jul 13, 2012 at 16:29
  • 1
    Couldn't you just make them private variables in your class in the file you're including? Commented Jul 13, 2012 at 16:33
  • 2
    maybe you should stop using the "include oriented programming" and start learning OOP Commented Jul 13, 2012 at 16:35
  • Sometimes, for simple processing scripts, object-oriented programming slows the development process down. :) But you're right--in most cases, OOP would prevent this from being an issue. Commented Jul 13, 2012 at 16:51

3 Answers 3

2

Wrap the include command into a include function.

    <?php
    //Führt die Cronjobs aus
    set_time_limit(30);

    /** Alle Dateien mit _cronjob am schluss sollen minütlich ausgeführt werden.*/
    $files = scandir(__DIR__ ."/cronjob");

    foreach($files as $file) {
        if($file == "." || $file == "..") continue;
        include_easy(__DIR__ ."/cronjob/". $file);
    }

    //Damit die variablen nicht überschrieben werden, wird das include über eine funktion gemacht.
    function include_easy($pfad) {
        include($pfad);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work in PHP 8.1.9 Declared variables still get included.
0

Unfortunately, at the time of this writing, it appears that wrapping what you want to include in a function or method is the only way to achieve this.

Comments

-2

Make your variables in the file your including private variables. That way they are included only in the file you want to inherit functions from. This is a much cleaner way to approach the problem.

1 Comment

You can't make variables in the global scope private, doesn't make any sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.