Good morning,
I am trying to to learn how the file inclusion in php works. Today, I am having a problem that I can not solve. This is my scenario:
Files at same directory:
- config.php
- db.php
- functions.php
- form.php
config.php
<?php
$config['json_file'] = 'test.json';
functions.php
<?php
function writeInFile()
{
echo $config['json_file']; // just for debugging porpuses
file_put_contents($config['json_file'], json_encode(time()));
}
model.php
<?php
class Model{
public function __construct();
function create()
{
writeInFile();
}
}
form.php
<?php
include('config.php');
include('functions.php');
include('model.php');
$model = new \Model();
$m->create();
When I execute the form.php I get this error:
Warning: file_put_contents() [function.file-put-contents]: Filename
cannot be empty in
functions.php
I know that this happens because the var $config['json_file'] is null inside of writeInFile() in functions.php. But, theorically it should works because I am doing the inclusion at the begginig of form.php. Or am I wrong?
Read variable scope from here [variable scope][1]
[1]: http://php.net/manual/en/language.variables.scope.php .
Right at the begining it sais that a function from another file that was included can't use a variable from another file beause it is considered to be in local scope . That's why you get error . Read more about var scope .
Related
I have a php class that uses "include" to load some html and php from a file. Within that file I want to access the class object that included the file, but I keep getting "Fatal error: Call to a member function makeSizesSelect() on a non-object ..."
I've tried both include and require, I've tried declaring globals, I've tried everything I can think of and everything I've so far found on SO. Nothing seems to allow the file I include to have php code access the object that included it.
Any ideas?
Here's a few snippets ...
The class file:
class cdf {
public $version = 001;
public function cdf_shortcode( $atts,$content )
{
$this->slog( 2,"shortcode() case: show" );
require( 'templates/container.php' );
}
}
And the required file container.php contains the following (amongst other stuff):
<?php
echo "version = ".$this->version;
?>
I then try to use the object:
$cdf = new cdf();
$cdf->cdf_shortcode( null, null);
The line $this->slog( 2,"shortcode() case: show" ) works. It runs that function (which I haven't included in this snippet) just fine. But then the file I require (or include) cannot use $this to access the object. I'm at a loss. :-(
All I want to do is access within the included file, the variables and methods in the class that included the file ...
Sorry, some added information. I'm not sure if this makes any difference. The code above is all part of a WordPress plugin.
Curious issue with a curious solution. I finally found the answer over here:
Possible to access $this from include()'d file in PHP class?
I tried all the obvious solutions this poster tried (globals, casting to another variable, etc) with the same lack of success. Turns out, just changing the file extension from .php to .tmpl fixed the issue, and my included file can now access the object that included it. Weird. (Of course, the downside now is that my IDE doesn't colour my code for me. :-( )
Thanks for your suggestions guys.
In the file you included you need to instantiate the class.
<?php
$yourClass = new cdf();
echo "version = ".$yourClass->version;
?>
When you want to access a function in a class, you need to instantiate the class first otherwise you wont have access to anything inside of it.
Also make sure the file you are including wont be included anywhere else where the class cdf doesn't exist because that will result in an error.
The variable $this can only access methods, variables, etc. only if they are in the same object.
Update based on your answer that seems to have worked:
Example.php
<?php
echo $this->returnString();
echo $this->randomVariable;
File.php
<?php
class IncludedClass
{
public $randomVariable = 123;
public function returnString()
{
return "some random string";
}
public function meh()
{
require_once('Example.php');
}
}
$meh = new IncludedClass();
$meh->meh();
I included a file over a template.class.php:
class template {
function loadtemplate() {
include_once("file.tpl");
}
}
after that I created a new object of the class using (in index.php):
$template = new template();
then I executed the method, to include the file (in index.php):
<?php $template->loadtemplate(); ?>
Now I want to execute a function defined in index.php in my file.tpl
error: Undefined variable: var.
How can I pass the variable? If I include the file directly in index.php without using the method, the variable is being passed.
found out a solution by myself:
function loadtemplate($var) {...}
in index.php
<?php $template->loadtemplate($var); ?>
I have a class named CMS which relies on a file names "DB.json"
I am using the following code:
class CMS{
function __construct(){
$DB = json_decode(file_get_contents("DB.json"));
}
}
which works fine as long as the file I am requiring the class from is inside the same directory
so if "/classes/cms/lib.php" is my class file and require "lib.php" inside the file "/classes/cms/form.php" then it will work
but if I require "/classes/cms/lib.php" from inside of a file such as "/home.php" then I get an error message saying that the file "DB.json" doesn't exist
link: http://www.streamlinedesign.ml/testcms.php
Use magic constant __DIR__ - it will indicate the directory of the current file (from which the constant is accessed):
class CMS{
function __construct(){
$DB = json_decode(file_get_contents(__DIR__.DIRECTORY_SEPARATOR."DB.json"));
}
}
I have a problem with classes which cannot be found in PHP.
The first thing I do is 'require_once' a file which 'require_once's all other files. When loading, no problems are showed. But when I start calling my function (Users::verificate();) I get the following error:
Fatal error: Class 'Users' not found in /Applications/XAMPP/xamppfiles/htdocs/sparks/dashboard.php on line 4
To test I've added a simple class with a function which only outputs a string with the echo method. This works so the problem has to be with this class. A MySql function which I call like this just works.
$mySql = new MySql();
$mySql->executeQuery('...');
The simple class has static a static function which I call like this (Oh, this works):
simple::launch();
In the Users class I'm calling non static functions from the MySql class from a static function. Can this be the problem?
Like another question here on SO suggested the problem isn't in using short php opening tags instead of the traditional php opening tag.
Even a little hint may help me :). Thanks for your time!
Edit:
I've added some relevant code from the User class. This is basically what it all looks like:
<?php
class Users {
public static function authenticate($email, $password) {
$mySql = new MySql();
$mySqlResult = $mySql->executeQuery("selectUser", [$email]);
...
}
public static function isAdmin() {
if ($_SESSION['isAdmin']) {
return true;
}
return false;
}
...
}
Edit 2:
I'm trying to show the flow:
From dashboard.php this are the first code lines:
<?php
require_once('code/init.php');
simple::launch();
if (!Users::verify()) {
header("Location: index.php");
}
?>
simple::launch(); is the code I used to test. This executes well. From this on the init.php file looks like this:
<?php
session_start();
require_once('simple.php');
require_once('MySql.php');
require_once('Users.php');
require_once('Projects.php');
The file names are correct as I get a visible error when these are wrong.
dashboard.php exists in the root. From there is a folder called 'code' which contains all these files.
#MbRostami gave the advice in a comment to use the 'get_required_files()' function to see which files are included. It turns out that the wrong files were loaded.
Root
| dashboard.php
| users.php
|- code
| Users.php
| init.php
In the init.php file the Users.php file (both files are in the code folder) was required. But for some reason the users.php file from the root was loaded. Some strange behaviour imho. Ahwell, that's something to investigate during the christmas days.
Problem is solved! Thanks!
Please review the example code below, I have a class file that is loaded into a config file. The config file is then loaded into any page I build. Is it possible to include a header file the way I have in the show_header() method? It doesn't seem to work so how can I achieve this result?
// Core.class.php
class Core
{
public function show_header($page_name){
require_once 'includes/header.inc.php';
}
}
// config.inc.php
require_once 'Core.class.php';
$core = New core;
// testpage.php
require_once 'config.inc.php';
$core->show_header('home');
Here is the top part of the header.inc.php file I am trying to include into the page, it seems to work including it but it breaks the way the header file works.
//header.inc.php
<?PHP
//start page timer
$session->get('user_id');
$profiler = new Profiler;
$profiler->start();
//see if site is turned on/off
$core->sitestatus($config['site_status']);
This part gives me errors like this...
Notice: Undefined variable: session in
C:\webserver\htdocs\friendproject2\includes\header.inc.php
on line 5
Fatal error: Call to a member function
get() on a non-object in
C:\webserver\htdocs\friendproject2\includes\header.inc.php
on line 5
When you're including a file from within a function it's just as if you wrote the code within that file from within that function.
e.g.
file foo.php:
<?php
echo $foo->getFoo();
file bar.php
<?php
class Foo {
public function getFoo() {return 'foo';}
}
$foo = new Foo();
function bar()
{
require 'foo.php';
}
bar();
The above will result in the following notice/error being thrown, because $foo is not known within bar().
Fatal error: Call to a member function getFoo() on a non-object in /Users/hobodave/foo.php on line 3
Edit:
I'm not sure what your "Core" class fully entails, but you could perhaps use it as a type of storage for your "globals".
e.g.
<?php
$session = new Session();
$core->session = $session;
Then your $session would be accessible in your header using $this->session
re your comment, sounds like you need a root web context object that you reference the other objects from:
$ctx = WebContext::get();
$ctx->session->get('x');
$ctx->input->get('y');
$ctx->identity->valid;
etc... this is how most web frameworks do it.
$session would need to be defined, then referenced in the included file:
// If a global variable:
global $session;
$session->get('x');
// If a member of Core:
$this->session->get('x');
yes you can do that, probably you'll want require instead of require_once, and the paths would need to be based on the current working directory or an absolute path
try adding error_reporting(E_ALL) to see if any notices are happening...
All calls you make inside the header file will be called as if they were local calls inside the show_header function. So if you want to use any global variable, you will have to use global $variablename; on the top of the included file (or in the beginning of the show_header function).
If you use a static function for the session class you wouldn't need to define it in the same file. http://php.net/manual/en/language.oop5.static.php
You are trying to access $session which is out of scope as pointed in another answer.
Since session stuff is usually global throughout most apps consider using the singleton pattern for the Session class.
This way you can do something like $session = Session::getInstance().
This lets you use the session class anywhere and you usually only one need one instance of a session class (usually). Take a look at Zend Framework for examples on singleton classes.