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();
Related
I have a a class stored in path plug/PHPDocumentParser/DocumentParser.php:
namespace LukeMadhanga;
class DocumentParser {
static function parseFromString($string) {
// do stuff
}
}
I want to call the class and function. I run this in a file that's stored at the base folder:
include_once("plug/PHPDocumentParser/DocumentParser.php");
$docObj = new DocumentParser();
$docText = $docObj->parseFromString('hello world');
I receive this error:
Fatal error: Class 'DocumentParser' not found
I am pretty sure the problem is how I call the class, correct?
You are calling static function in wrong way. Try
DocumentParser::parseFromString()
Also use require_once, you will know if it was included correctly. (maybe path is wrong.)
Edit : Ok, you added namespace now - it should be \LukeMadhanga\DocumentParser::parseFromString() thats also why you dont get instance of DocumentParser using new.
Of course you can always add use keyword at top of your file to include your namespace.
I'm going crazy over these past few days and I really need your help because I don't know what else to do. I tried everything.
Here is the problem:
I have two files. site.php and logs.php.
Here is the content of logs.php:
class Logs {
function __construct() {
}
}
Now comes the fun part, beginning of 'site.php':
require_once("database.php");
require_once("logs.php");
class Site {
private $db;
private $logs;
function __construct() {
$this->logs = new Logs(); ### this is the error line
$this->db = new MySQLDatabase();
}
}
They are all in the same directory. Why can't it find my class?
PHP might be including the wrong the file. PHP will search the include path before looking inside the script's directory. You may somehow have a logs.php in your include path (See This PHP manual for details.) I suggest maybe adding an echo "hello world"; in the root of your logs.php.
You might also have accidentally enclosed the class inside another class or function. Make sure the class is only inside the tags.
Thank you all for helping. I have found out what the problem was! Turns out, for some reason I shouldn't name my php file 'logs.php'. As soon as I renamed it, it works perfectly. I have no idea why but it just wont work with that name.
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);
I am including one PHP script into another using PHP's require_once() method. This script contains a class, TemplateAdmin, which instantiates itself right after the script, like this:
class TemplateAdmin {
// Class body...
}
$templateAdmin = new TemplateAdmin();
This was working fine for a while. However, I have adopted a new importing technique to include classes and packages. I have tested this new technique, and it works! However, for some strange reason, none of the methods in any of the classes I import are there when I need them. However, it seems as though the instance variables are still there.
For example, when a class with this absolute path is called:
require_once("C:\wamp\www\wave_audio\system\server\templates\TemplateAdmin.php");
... I get this error in the call stack:
Fatal error: Call to undefined method stdClass::top() in C:\wamp\www\wave_audio\cms\index.php on line 189
This error is referring to my use of the top() method inside of the TemplateAdmin class.
Does any one have any idea as to why this is happening??? If this helps, I have been using require_once() all along, I am running PHP 5.3.5 on a Windows XP Media Center machine.
Thank you for your time!
Assuming you dont want to use globals here is one way that only requires a few changes.
TemplateAdmin.php:
class TemplateAdmin {
// Class body...
}
return new TemplateAdmin();
Return include once in import:
function import($classes) {
//Convert ECMAScript style directory structures to Unix style
$address = str_replace(".", "/", $classes);
$address = INSTALL_ROOT . "system/server/" . $address . ".php";
if (file_exists($address) && is_file($address)) {
return require_once($address);
} else {
die(""" . $classes . "" does not link to an existing class");
}
}
Assign the variable:
$adminTemplate = import('templates.TemplateAdmin');
I have a feeling your php error message is accurate. I know on your stripped down version, you pieced it together how you're sure it's setup but it's obviously not a direct copy/paste since it's like:
class TemplateAdmin {
public function top() {
//The "top" method...
}
}
So, the error message says that the method "top" is not defined. If it were not including your file properly, it would tell you that the class you instantiated doesn't exist. Either that method does not exist in the class you think it is, or the method has been unset somewhere in that object instance. Trust your error message.
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.