PHP类属性没有传入方法

问题描述:

首先,我对PHP非常陌生,并试图理解如何使用对象类。PHP类属性没有传入方法

几天来,我遇到了一个我一直无法解决的挑战。问题是一个类的属性没有在类的一个方法中被调用/使用。我知道这个属性并不是空的,因为我投入了一个测试方法来确认它。

必须有一些我错过了,我希望它不是很明显,因为我已经花了几天尝试不同的解决方案无济于事。

下面是我的代码注释:

<?php 
/************* global variables ******************************/ 
$company_name = "Stay Cool HVAC"; 
$street = '12345 Rockwell Canyon Rd.'; 
$company_citystatezip = "Hometown, CA 91777"; 
$company_address = "<center>$company_name <br/> ". "<center>$street <br />". "<center>$company_citystatezip"; 

/************* end global variables **************************/ 

echo '<H1 align="center">PHP Class Example</H1>'; 

class Company { 
//// insert object variables (properties) 
var $address; 

//// insert methods below here 

//// Test to see that address property is set to $company_address variable 
function __get($address){ 
    return $this->address; 
    } 

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;          
    } 

//// The address property isn't passing to output in method 
function getFooter($color) { 
    $this->address; 
    $bottomfooter = "<TABLE align='center'; style='background-color:$color;width:50%'><TR><TD>"; 
    $bottomfooter .= "<center><b><u>$address</center></b></u>"; 
    $bottomfooter .= "</TD></TR></TABLE>"; 
    return $bottomfooter; 
    } 
} 

$companybanner = new Company(); 
echo $companybanner->getHeader($company_name, gold); 
echo "<br/>"; 
$companybanner->address = "$company_address"; 
echo $companybanner->getFooter(blue); 

// Test to confirm that "address" property is set - working 
echo "<br />"; 
echo $companybanner->getaddress; 
?> 

希望你可以看到“地址”属性是假设从“getFooter”方法的蓝色表格内输出。相反,我的结果是没有文字的蓝线。另外,“地址”属性不为空,因为我确实使用“__get($ address)”方法进行了测试。

任何想法我做错了什么?

+1

变化' “

$地址
”;''到“
$这个 - >地址
”;',它会工作,你希望它的方式。 –
+0

尝试$ this-> address –

也许你应该更换

function getFooter($color) { 
    $this->address; 

随着

function getFooter($color) { 
    $address = $this->address; 

我understaind PHP的行为方式,这条线

$bottomfooter .= "<center><b><u>$address</center></b></u>"; 

会尝试使用本地变量(本地的功能)$地址,但$地址没有定义。据我了解PHP是如何工作的 - 这条线

$this->address; 

会以这种方式来解释:如果地址=“ABC”是一样的,告诉翻译做

"abc"; 

指定任何操作。我想$ address = $ this-> address;不是解决您的问题的唯一方法。我认为你可以用这个很好:

$bottomfooter .= "<center><b><u>{$this->address}</center></b></u>"; 

希望有帮助。

+0

正如不同的人所指出的,解决方案是在“getFooter”方法内用“$ this-> address”替换“$ address”。我感谢每个人都给出了一个快速的答案,因为我是一个noob,他们的知识非常感谢。 再次感谢您。 –