Jump to content

Recommended Posts

If I create an instance of an object in index.php and within index.php include header.php.  Can I have code in my header.php that uses the object as if it were in the file?

index.php
[code]
<?php
$site = new SiteCore;
print $site->name;

include(header.php)

?>
[/code]

header.php
[code]
<title><?php print $site->name ?><title>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/33496-using-a-class-in-an-included-file/
Share on other sites

Here is my code...the relevant parts anyway.
SiteCore.php
[code]
<?php
Class SiteCore {

private $_DOC_ROOT;
private $_HEADER;
private $_FOOTER;
private $_IMAGES_DIR;
private $_INCLUDE_DIR;
private $_NAME;
private $STYLESHEET;

function __construct() {
$this->_DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$this->_IMAGES_DIR = $this->_DOC_ROOT . "/images";
$this->_INCLUDE_DIR = $this->_DOC_ROOT . "/include";
$this->_NAME = "Family and Friends";
$this->_HEADER = $this->_INCLUDE_DIR  . "/header.php";
$this->_FOOTER = $this->_INCLUDE_DIR . "/footer.php";
$this->_STYLESHEET = $this->_INCLUDE_DIR . "/stylesheet.css";
}

        public function print_header() {
$header = $this->_HEADER;
if (file_exists($header)) {
require($header);
} else {
print "Header File Missing!";
}
}       

        public function name() {
return $this->_NAME;
}
}
?>
[/code]
index.php
[code]
<?php
Require($_SERVER['DOCUMENT_ROOT'] . "/classes/SiteCore.php");

$site = new SiteCore;

$site->print_header();

print $site->name();

$site->print_footer();

?>[/code]
header.php
[code]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css"
href="<? print $site->print_css();?>" />
<title><?php print $site->name() ?></title>    <!-- **  FAILING!  ** -->
</head>
<body>
<div>  <!-- GLOBAL CONTAINER -->
<?
print $site->name();
?>[/code]
I think I see what you are saying.  Since I included the header from within in the class method and not directly from index.php it cannot see $site?  Like my header file is "running" inside of my SiteCore::print_header() method?

I made the change and it worked!  Thank you!

Is what I'm doing a bad practice?
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.