我一直在努力让一个数组在类中初始化。我想尝试的是使用数组和子类创建一个侧面菜单。我试图解决这个问题好几天了,现在我正在寻求帮助。我有一种感觉,我错过了一些基本的东西,因为我只是在学习PHP。
下面是我的代码,注释掉的行是尝试解决方案但没有奏效。
<?php
/************* global variables ******************************/
//global $house_array, $car_array, $vacation_array, $company_address;
$company_name = "Heaven HVAC";
$street = '12345 Blue Canyon Rd.';
$company_citystatezip = "Heaven, CA 91777";
/************* end global variables **************************/
echo '<H1 align="center">Calling Array inside Child Class</H1>';
class Company{
//// insert object variables (properties) HERE
var $company_url = "http://localhost";
var $company_email = "example@example.com ";
//// insert methods here
function getHeader($company_name, $color) {
$topheader = "<TABLE align='center'; style='background-color:$color; width:50%'><TR><TD>";
$topheader .= "<H1 style='text-align:center'>$company_name</H1>";
$topheader .= "</TD></TR></TABLE>";
return $topheader;
}
function getFooter($color) {
$this->address;
$bottomfooter = "<TABLE align='center'; style='background-color:$color;width:50%'><TR><TD>";
$bottomfooter .= "<center><b><u>$this->address</center></b></u>";
$bottomfooter .= "</TD></TR></TABLE>";
return $bottomfooter;
}
} // end class Company
//// Working On child class - If commented out, then the code has been tried and failed
class AirCondition extends Company {
var $navbar_array;
//// create array
function create_navbar_array ( ) {
$mainurl = $this->company_url;
$this->navbar_array = array( "Home Page"=>"$mainurl?whichpage=home", "Sales"=>"$mainurl?whichpage=sales",
"Support" => "$mainurl?whichpage=support", "Contacts" => "$mainurl?whichpage=contact" );
}
//create_navbar_array();
// return $navbar_array;
function getLeftNavBar($array){
// create_navbar_array();
## Create a table to display arrays
print "<TABLE BORDER='1'>";
echo '<tr><td>Navigation Menu</td></tr>';
foreach($array as $Page){
echo "<tr><td>{$Page}</td></tr>";
return $array;
}
echo "</TABLE>";
}
}
$HVACcompany = new AirCondition();
$HVACcompany->address = "777 Estate Rd <br /> $company_citystatezip";
echo $HVACcompany->getHeader($company_name, orange);
echo "<br/>";
echo $HVACcompany->getFooter(green);
//echo $HVACcompany->getLeftNavBar();
//echo $HVACcompnay->create_navbar_array();
//$HVACcompnay->create_navbar_array();
$HVACcompany->getLeftNavBar($navbar_array);
?>
我可以创建网页布局,但是数组没有初始化。我做错了什么/错过了什么?
答案 0 :(得分:1)
以下一行:
$HVACcompany->getLeftNavBar($navbar_array);
应该是:
$HVACcompany->getLeftNavBar($HVACcompany->navbar_array);
因为$ navbar_array从未在全局命名空间中声明,但是它被声明为AirCondition类中的公共变量,该变量是使用变量$ HVACcompany初始化的。
此外,您需要调用函数$HVACcompany->create_navbar_array();
在调用$HVACcompany->getLeftNavBar($HVACcompany->navbar_array);
之前创建数组$ navbar_array。
同时删除foreach循环中的return $array;
语句。