PHP global include? - php

I have a seperate PHP file I include that has a several important functions on it. I also have a file called variables.php which I include into each function so I can call some important variables too. Is there a way to just call variables.php at the top of the page, instead of inside each function manually? I just thought it would be easier if there was a way to do like a 'global' include or something.

You can set auto_prepend_file in the INI or .htaccess file to automatically include a file.

Well, if they are constant variables (AKA they don't change) you can define a constant instead
define("CONSTANT_NAME", "constant_value");
Or as of PHP5.3
const COSTANT_NAME="constant_value";
Then you can access them in every function
function test(){
echo CONSTANT_NAME;
}

Related

how to include a php file inside a public function in Joomla?

I want to include/require_once a PHP file inside a template with the help of a class. It's not including the file as it should be. Only showing the top html part of the file.
In place of JPATH_BASE, I have tried other options also.
class xyz {
public function loadfile($block) {
require_once JPATH_BASE.'/templates/'.$block.'.php';
}
}
$app = new xyz();
$app->loadfile(top);
A help will be very much appreciable.
When you include a file inside a function, remember that it will be executed in its context, which is very likely to break some things for some code. (for example all globals will be undefined without calling global statement before)
For example, consider you add this to your class xyz:
private function test() {
echo 'test';
}
Now, in the included file you can put:
<?php
$this->test();
Now if you load this file using this class, test will be outputted.
The question is why do you want to load files with a help of the class and a function and if it's really neccessary.
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.
(https://php.net/manual/en/function.include.php)
(also, about only top part of the page being shown, check the file that is being included, what it really contains; also check for errors in your server log, they will let you more easily spot the issue)

Can I create a function in PHP that works as a system function (as echo,die, etc)

I'm always using a function to write to a log file, but this function is defined in a file among many other things that I don't need to include.
I was wondering, is it possible to define a function somewhere inside php to make it available without the need to include the source file? Sort of like how I can just use echo or die, or isset. Could I create my own function to use it this way?
Thank you.
No. To do that, you'll have to write a PHP extension in C. Any PHP code will always need to be included explicitly one way or another.
PHP has the option to always automatically include a file at the beginning though: http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
Actually, you need to make a module with your function.
Other ways:
make autoload. http://www.php.net/manual/en/language.oop5.autoload.php
put only this function to other file and include it everytime you need.
you can add you log class in set_include_path path or add this function to pear library class

How to include/require file trough function PHP?

I have 2 files, class.inc.php and index.php.
class.inc.php contains Myclass and few functions, index.php file spits out functions from class.inc.php.
Now I need to create a function which will include/require a file and that function should actually require that file in index.php not in class.inc.php.
Yes I know I can place my file in a function and call it that way but we have to keep it in files because of some future MVC overrides. I do not want to include a file in index.php directly either if all possible. So is there a way to do this?
In my index.php I should be able to do this:
Myclass::include(PARAMS);
and that should include a file name params.php located somewhere else.
I tried this in class.inc.php
abstract class Myclass {
static function load($filename){
require_once $filename;
}
}
and this in
index.php
Myclass::include(PARAMS);
but none of my variables from params.php are visible in index.php because they seem to be in class.inc.php.
include, require and friends basically act as though you had copied-and-pasted the contents of the file to that location. So if you run them in a function, any "bare" variables, which would be global if you ran the file on its own, are instead local to that function.
Generally speaking, the answer in modern PHP code is simply not to use any global variables - a file should contain only functions, or better still, only namespaces and classes, with all the variables wrapped up in those.
If you really need to have global variables, however, you can use the global keyword either in your include function or at the top of the included file.
So for instance if your included file defines a variable $config which needs to be accessed elsewhere, at the top of the file you can write global $config; to push it out of any scope you're in when you include/require it.

PHP $var undefined when using multiple require()

I'm setting a $baseurl in a settings.php file.
In my index.php, I've got 3 require() in a row for the settings.php/header.php/masthead.php.
When I come to echo out the $baseurl it's undefined. If I define the $baseurl within the header.php then it works within the header.php file.
How can I get the $baseurl to be defined within the settings.php file and usable within each require() ?
Order of inclusion
The file that sets $baseurl must be require_once() first for the subsequent files to have access to the variable.
Function Scope
If you are defining $baseurl in a function or the files are require_once() from within a function then $baseurl will be trapped in that functions scope. This would the case if settings.php looked something like:
<?php
function setup_config() {
$baseurl = 'http://www.example.org';
}
Or requiring from within a function
<?php
function include_a_file($file) {
require_once 'my/base/path/' . $file;
}
This is documented in the Variable Scope portion of the PHP Manual.
One way to work around this is to add $baseurl as an element in $GLOBALS array instead of as a standalone variable:
$GLOBALS['config']['baseurl'] = 'my/base/url/';
Note I have added the ['config'] element to namespace your config away from anything else you may be tempted to place in $GLOBALS.
variable unset()
Another possibility is that you might be calling unset($baseurl) somewhere else in the code, which would be marking the variable as undefined.
If you define it in settings.php, it should be available in the global scope of all the included scripts. When you enter a function, the scope changes so the variable won't be available unless you 'import' it by declaring global $baseurl; at the start of the function (not advised, though).
If settings.php is included first, and $baseurl is defined as a global variable in settings.php, it will be available in all subsequently included files. If the variable is defined inside a function in settings.php, it will need to be defined as a global there:
$GLOBALS['baseurl'] = 'theurl';
If it is accessed within a function in any of the subsequently included files, it will need to be accessed via $GLOBALS[] there too:
echo $GLOBALS['baseurl'];
If you are expecting to access a global variable from multiple files, it is highly recommended to always use the $GLOBALS[] array since it remains clear in any scope that the variable is being set and accessed globally.
If you require() the files in a function, the variables are defined in the scope of the function: They are not global.
Use $GLOBALS['baseurl'] = '...'; in settings.php

Can you pass values to included files in PHP without using globals?

A pattern I tend to use often in PHP is setting a few globals (such as $page, $user, $db, etc), and then including a file which uses those globals. I've never liked the idea of using globals for this, though, so I'm looking for a better way.
The obvious solution is to define a class or function in the subfile, and call it after the file is included. There are cases where that can't work though, such as this:
// Add entries to a URI table from each section of the site
global $router;
$router = new VirtualFileSystem();
$sections = array('store', 'forum', 'blog');
foreach($sections as $section)
include dirname(__FILE__) . $section . '/routing.php';
// Example contents of 'forum/routing.php'
// implicitly receive $router from caller
$router->add('fourm/topic/', 'topic.php');
$router->add('forum/topic/new/', 'new_topic.php');
// etc
If I tried to wrap each routing.php in a function and call them each with $router as an argument, the same function name would clash after being defined in multiple files.
I'm out of ideas. Is there a better way to pass variables to included files without polluting the global namespace?
include and its siblings are basically just copy-paste helpers, and the code inside them shares scope with the calling block - as if you'd copy & paste it just where the include statement is. The sane way of using them is to think of them the same way you'd use #include in C or using in C# or import in Java: import some code to be referenced later on. If you have code in the included file that needs parameters, then wrap it in a function, put the parameters in the function arguments, use include_once at the top of the including file, and call the function with the parameters you want, wherever you need to. No globals required. As a rule of thumb, in regular operation, putting any code that "does" something (executes statements in the global scope) in an included file is best avoided IMO.
No, there is not. You're not passing variables to included files anyway. The code that is included behaves as if it was written where the include statement is written. As such, you're not passing variables into the included file, the code in the file can simply use the variables that are in scope wherever the include statement is located.
In your case the contents of forum/routing.php are not really standalone code, they're code snippets that depend on a very specifically set up scope to function correctly. That's bad. You should write your includable files in a way that does not couple them to the including code. For example, you could make your Router a static class and call it statically in forum/routing.php:
require_once 'virtual_file_system.class.php';
VirtualFileSystem::add('forum/topic/', 'topic.php');
As long as there is a class VirtualFileSystem in your app, this will work, and won't pollute the namespace any more than it already is anyway.
just isolate includes in a function:
function add_entries_to_router($router, $sections) {
foreach($sections as $section)
include dirname(__FILE__) . $section . '/routing.php';
}
$router = new VirtualFileSystem();
add_entries_to_router($router, array('store', 'forum', 'blog'));
You can try an OOP way by making a Configuration class as a singleton and retrieving it when you need it.
You could define magic methods for __get and __set to add them to an private array var and make the constructor private.
I usually define as constant only the path to my src project in order to load class files quickly and properly (and use some SPL too).
But I agree with #tdammers about the fact that an include keep the environment variables like if you were on the caller file (the one who makes the include).

Categories