Passing variable over class to included file - php

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); ?>

Related

Template class stops another class from working

Trying to get a simple template system working, but it seems to affect another class.
I have two PHP classes, both called in index.php:
HeaderData.php - class allows user to setup Header data, eg doctype,
charset.
PageTemplates.php - class allows user to include a template file.
When I call the HeaderData class, then manually require() a template file from view (ie contains doctype, head, meta tags etc), the code from the header class works fine in the template file, outputting the objects from the header class such as Doctype etc.
However, when I try to use the PagesTemplate class to include the template file (with manual require() removed from index.php), the template file is included, but the HeaderData class no longer works in it.
Error log shows:
Notice: "Undefined variable varHeaderData";
Error: "Call to a member function PageDoctype() on a non-object";
Both the variable and function worked fine when manually require() the template file in index.php.
The code below is dev only (data checks etc to be added):
index.php:
// Use HeaderData Class
$varHeaderData = new HeaderData(
array(
'PageDoctype' => '<!DOCTYPE html>',
'PageCharset' => 'UTF-8',
));
// Use PageTemplates Class
$varPageTemplate = new PageTemplates();
$varPageTemplate->LoadTemplate('template-file.php');
PageTemplates.php Class:
class PageTemplates
{
private $strTemplatesDir = 'view/templates/';
public function __construct($strTemplatesDir = NULL)
{
if ( is_dir($strTemplatesDir) )
{
$this->strTemplatesDir = $strTemplatesDir;
}
}
public function LoadTemplate($strTemplateFile)
{
{
require_once ($this->strTemplatesDir.$strTemplateFile);
}
}
}
template-file.php:
echo $varHeaderData->PageDoctype();
The HeaderData class simply sets the object the user entered in the array with the PageDoctype() function in the class (again this works fine without the page template class)
Can someone tell me why when using the template class to require() the template file, it stops the objects from the HeaderData from working in the template-file.php?
The simplest way to do it is to pass variable in to the LoadTemplate method as an array and use extract function:
public function LoadTemplate($strTemplateFile, $vars = array())
{
extract($vars);
require($this->strTemplatesDir.$strTemplateFile);
}
And in the index.php
...
$varPageTemplate->LoadTemplate('template-file.php', array(
'varHeaderData' => $varHeaderData
));
One of your errors says: "Call to a member function PageDoctype() on a non-object", so make sure that PageDoctype() method is defined in the HeaderData class.

context of file inclusion in php

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 .

PHP Fatal error: Call to undefined function when function is defined

I am getting an error in PHP:
PHP Fatal error: Call to undefined function getCookie
Code:
include('Core/dAmnPHP.php');
$tokenarray = getCookie($username, $password);
Inside of dAmnPHP.php, it includes a function called getCookie inside class dAmnPHP. When I run my script it tells me that the function is undefined.
What am I doing wrong?
It looks like you need to create a new instance of the class before you can use its functions.
Try:
$dAmn = new dAmnPHP;
$dAmn->getCookie($username, $password);
I've not used dAmn before, so I can't be sure, but I pulled my info from here:
https://github.com/DeathShadow/Contra/blob/master/core/dAmnPHP.php
How to reproduce this error:
Put this in a file called a.php:
<?php
include('b.php');
umad();
?>
Put this in a file called b.php:
<?php
class myclass{
function umad(){
print "ok";
}
}
?>
Run it:
PHP Fatal error: Call to undefined function umad() in
/home/el/a.php on line 4
What went wrong:
You can't use methods inside classes without instantiating them first. Do it like this:
<?php
include('b.php');
$mad = new myclass;
$mad->umad();
?>
Then the php interpreter can find the method:
eric#dev ~ $ php a.php
ok

Can I have a class method include a header file for me in PHP?

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.

How can I initiate a PHP class and use it in several files?

I am stumped right now. In my last post about this question the answer was to use a singleton to make sure an object is only initiated 1 time but I am having the opposite problem.
If I have a file called index.php and then I include these files into it, class1.php, class2.php, class3.php, class4.php.
In index.php I will have,
<?PHP
$session = new Session();
require_once '/includes/class1php';
require_once '/includes/class2.php';
require_once '/includes/class3.php';
require_once '/includes/class4.php';
?>
then in all 4 of the test files I will try to access a method called get() from the session class, assume the session class file is already included into the index.php page as well.
Now if I try to use...
$testvar = $session->get($var1);
in any of the test class files I will get this error
Fatal error: Call to a member function get() on a non-object
the only way the code works without an error is if I use
$session = new Session();
in every file.
How can I fix/avoid having to initaite the class in every file when it is already initated in the index.php file?
the goal is to let me initiate a class in 1 file like index.php and then include the class files into that page, the catch is most of the classes use methods from other classes so would be nice if I didn't have to initiate every class in every file
Without seeing the code it's hard to tell, but I think I can make some assumptions. correct me if I'm wrong:
EDIT: So post your source so we can stop speculating
1) The files you are including are class files. in other words, they contain something like:
class a
{
function a(){}
function b()
{
}
}
2) You aren't trying to execute code in the class files, at load time, but at some later time by instantiating them
i.e.
require("class.a.php");
$myA = new a();
$a->b();
If you are trying to reference your session variable inside those classes, then you have a scope issue. A variable declared outside a class definition can't be used inside the class, unless it is declared as a global var inside the class.
class a
{
function a(){}
function willFail()
{
$session->doSomething(); //fails
}
function b()
{
global $session;
$session->doSomething(); //succeeds
}
}
Even then, you probably don't want to do that, but instead you should pass in your session as a variable if the class needs access to it:
class a
{
function a(){}
function b($session)
{
$session->doSomething(); // yay!
}
}
You could have a base class they all all extend from
Example
class test1 extends Base {
public function doSomething() {
$this->session->get('something');
}
}
class Base {
protected session;
public function __construct() {
$this->session = new Session();
}
}
You're kind of thinking about it backwards. Any file that will use the session object will need to include the file containing that class definition. The alternative is to use __autoload to pull the class in:
function __autoload($classname)
{
if ($classname == 'Session')
{
include_once 'Session.php';
}
}
EDIT : you'll need to put the file containing that autoload into every file that will use it.

Categories