Jump to content

Using a class in an Included file


snivek

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.