我有一个functions.php文件,除其他功能外,还包括以下内容:
function head() {
global $brand, $brandName, $logo, $slogan, $siteName, $title, $titles, $keyword, $keywords, $description, $descriptions, $bodyclass, $bodyClass, $page;
include('_assets/inc/head.php');
}
function foot() {
global $brand, $brandName, $logo, $slogan, $siteName, $title, $titles, $keyword, $keywords, $description, $descriptions, $bodyclass, $bodyClass, $page;
include('_assets/inc/foot.php');
}
我需要将全局变量行复制到foot()
以获取我在foot.php中调用的变量来显示。我没有地方集中这些全局变量,所以我只需要在我的网站中放置一次全局行吗?
按照杰克的指示,我现在有:
class Page {
private $context;
public function __construct(array $context) {
$this->context = $context;
}
public function printHead() {
extract($this->context);
include '_assets/inc/head.php';
}
public function printFoot() {
extract($this->context);
include '_assets/inc/foot.php';
}
}
$page = new Page(array(
'brand' => 'myBrand',
'brandName' => '<span class="brand">'.$brand.' <sup><span aria-hidden="true" class="icon_search"></span></sup></span>',
'logo' => '<a href="/" class="brand">'.$brandName.'</a>',
'slogan' => '<span class="slogan">Find A Real Estate Professional</span>',
'siteName' => $logo.' | Directory of Real Estate Professionals',
'title' => 'Directory of Real Estate Professionals | '.$brand.'',
'titles' => array (
'home' => 'Find A Real Estate Professional | '.$brand.''
);
if(isset($titles[$page])){
$title = $titles[$page];
}
'keyword' => ''.$brand.', real estate professionals, real estate directory, real estate agents, realtor directory, real estate brokers, real estate lawyers, real estate insurance agents, real estate appraisers, real estate staging consultants',
'keywords' => array (
'' => ''
);
if(isset($keywords[$page])){
$keyword = $keywords[$page];
}
'description' => ''.$brand.' is a complete directory of real estate professionals, including agents, brokers, appraisers, insurance agents, stagers, lawyers, and more.',
'descriptions' => array (
'' => ''
);
if(isset($descriptions[$page])){
$description = $descriptions[$page];
}
'bodyclass' => ' page bbfix',
'bodyClass' => array (
'home' => 'home'
);
if(isset($bodyClass[$page])){
$bodyclass = $bodyClass[$page];
}
'page' => $page
));
$page->printHead();
$page->printFoot();
但是,我的代码存在与数组相关的错误。 :(
答案 0 :(得分:5)
请不要跳到像global
这样的结构和同样糟糕的$GLOBALS
;全球状态为not recommended。
也就是说,通过使用对象封装您的状态,您可以通过一些小的更改来改进您的设计:
class Page
{
private $context;
public function __construct(array $context)
{
$this->context = $context;
}
public function printHead()
{
extract($this->context);
include '_assets/inc/head.php';
}
// same for foot()
}
使用它:
$page = new Page(array(
'brand' => 'foo',
'brandName' => 'bar',
// etc
));
$page->printHead();
Page
类在构造时封装上下文;在您的资产包含在脚本中之前提取此状态。对于包含的脚本,就好像变量一直是全局的。
答案 1 :(得分:2)
是的,对PHP中的所有全局变量都有一个集中引用。它被称为the $GLOBALS
array。
一个关联数组,包含对当前在脚本全局范围内定义的所有变量的引用。变量名是数组的键。
例如:
$GLOBALS['brand'];
$GLOBALS['logo'];
// And so on