2016-03-09 76 views
0

首先,我對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 –

回答

1

也許你應該更換

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,他們的知識非常感謝。 再次感謝您。 –

相關問題