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 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!
I'm having trouble with accessing the session in an external .php script located in webroot.
Thought I'd write a function getSession() in one of my controllers and try to call it in the .php file.
So in steps:
I have file.php
In a controller I have a function getSession().
How to call the controllers function in the file.php?
Thank you.
EDIT
Meanwhile I fixed my bug, but still am curious how this is done and want other stack users to find a good answer to this so:
Its exactly like this:
In UsersController I have a function:
public function getSession() {
return $_SESSION['Auth']['User']['user_id'];
}
That I want to let's say print (for example) like this: print_r(Users.getSession) in the file test.php located in webroot/uploadify/test.php.
This file is not a class, but if it is required, then it shall be :)
#CaboOne: Maybe your answer was correct, I just wasnt sure what code to call (and enter) where :)
Supposed I have the following php file in webroot folder:
<?php
class TestingClass {
function getName(){
return "Test";
}
}
?>
I would do the following:
// This would bring you to your /webroot folder
include $_SERVER['DOCUMENT_ROOT'].'/another_file.php';
// Initializing the class
$example = new TestingClass;
// Call a function from the initialized class
$a_value = $example->getName();
// If you want to use $a_value in the view, you can then set
$this->set('a_value', $a_value);
Hi I have a class as follows:
<?php
include '(OrderContainer.php)';
class OrderAuthenticator
{
private $OrderObj;
public function __construct($Order)
{
$this->OrderObj = $Order;
echo 'Created an instance os OrderContainer<br/>';
}
//Misc methods.....
}
?>
Then I have a method that tries to instantiate this object
<?php
include ('OrderAuthenticator.php');
$Authenticator = new OrderAuthenticator($OrderObj);
?>
Problem is that in the object is not instantiated.....
No matter what I do ..... Im new to PHP so I was wondering if there is something quite obvious here that Im not doing?
Could someone please give me a hand..
Thanks
It seems as include '(OrderContainer.php)'; should be include('OrderContainer.php'); instead.
Make sure $OrderObj is defined in the main script creating an instance of OrderAuthenticator.
To debug, be sure that PHP is showing error messages by starting with error_reporting(E_ALL); ini_set('display_errors',1); first in the main script.
Also, make sure you have no syntax error (for example, by printing "Hello world" in your script).
You need to create an $OrderObj to be passed in to the constructor
Just remove public from constructor.
I have a function(this is exactly how it appears, from the top of my file):
<?php
//dirname(getcwd());
function generate_salt()
{
$salt = '';
for($i = 0; $i < 19; $i++)
{
$salt .= chr(rand(35, 126));
}
return $salt;
}
...
And for some reason, I keep getting the error:
Fatal error: Cannot redeclare
generate_salt() (previously declared
in
/Applications/MAMP/htdocs/question-air/includes/functions.php:5)
in
/Applications/MAMP/htdocs/question-air/includes/functions.php
on line 13
I cannot figure out why or how such an error could occur. Any ideas?
This errors says your function is already defined ; which can mean :
you have the same function defined in two files
or you have the same function defined in two places in the same file
or the file in which your function is defined is included two times (so, it seems the function is defined two times)
To help with the third point, a solution would be to use include_once instead of include when including your functions.php file -- so it cannot be included more than once.
Solution 1
Don't declare function inside a loop (like foreach, for, while...) ! Declare before them.
Solution 2
You should include that file (wherein that function exists) only once. So,
instead of : include ("functions.php");
use: include_once("functions.php");
Solution 3
If none of above helps, before function declaration, add a check to avoid re-declaration:
if (!function_exists('your_function_name')) {
function your_function_name() {
........
}
}
You can check first whether the name of your function exists or not before you declare the function:
if (!function_exists('generate_salt'))
{
function generate_salt()
{
........
}
}
OR you can change the name of the function to another name.
You're probably including the file functions.php more than once.
In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.
This answer explains why you shouldn't use function inside function.
This might help somebody.
I had strange behavor when my *.php.bak (which automaticly was created by notepad) was included in compilation. After I removed all *.php.bak from folder this error was gone.
Maybe this will be helpful for someone.
Another possible reason for getting that error is that your function has the same name as another PHP built-in function. For example,
function checkdate($date){
$now=strtotime(date('Y-m-d H:i:s'));
$tenYearsAgo=strtotime("-10 years", $now);
$dateToCheck=strtotime($date);
return ($tenYearsAgo > $dateToCheck) ? false : true;
}
echo checkdate('2016-05-12');
where the checkdate function already exists in PHP.
I would like to add my 2 cent experience that might be helpful for many of you.
If you declare a function inside a loop (for, foreach, while), you will face this error message.
I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.
Declare your function as a lambda expression (I haven't seen this solution mentioned):
$generate_salt = function()
{
...
};
And use thusly:
$salt = $generate_salt();
Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.
I'd recommend using get_included_files - as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.
require_once is also useful if the file you're attempting to include is essential.
I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')
Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.
means you have already created a class with same name.
For Example:
class ExampleReDeclare {}
// some code here
class ExampleReDeclare {}
That second ExampleReDeclare throw the error.
If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.
I had this pop up recently where a function was being called prior to its definition in the same file, and it didnt have the returned value assigned to a variable. Adding a var for the return value to be assigned to made the error go away.
You have to deactivate the lite version in order to run the PRO version.
This errors says your function is already defined ; which can mean :
you have the same function defined in two files
or you have the same function defined in two places in the same file
or the file in which your function is defined is included two times (so, it seems the function is defined two times)
I think your facing problem at 3rd position the script including this file more than one time.So, you can solve it by using require_once instead of require or include_once instead of include for including your functions.php file -- so it cannot be included more than once.
or you can't create function in loop
such as
for($i=1; $i<5; $i++)
{
function foo()
{
echo 'something';
}
}
foo();
//It will show error regarding redeclaration