php數組{array}使用教程
現在,這冗長的設定每個屬性使用一套方法-必須有一個更簡單的方法。這就是關聯數組結合我們構造派上用場。讓我們創造我們的用戶對象,並給它幾個實例時性能
$attribs = array(
'name' => 'Kirupa',
'job' => 'Engineer',
'school' => 'MIT',
'homeTown' => 'Spanish Fort',
'homeState' => 'Alabama'
);
$kirupa = new User( $attribs );
echo 'Name: '.$kirupa->getName().'<br />'; // Kirupa
echo 'Job: '.$kirupa->getJob().'<br />'; // Engineer
echo 'School: '.$kirupa->getSchool().'<br />'; // MIT
echo 'Home Town: '.$kirupa->getHomeTown().'<br />'; // Spanish Fort
echo 'Home State: '.$kirupa->getHomeState().'<br />'; // Alabama
class User {
private $name;
private $job;
private $school;
private $homeTown;
private $homeState;
function __construct( $attribs ) {
$this->name = $attribs['name'];
$this->job = $attribs['job'];
$this->school = $attribs['school'];
$this->homeTown = $attribs['homeTown'];
$this->homeState = $attribs['homeState'];
}
/* name methods */
function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}
/* job methods */
function setJob( $val ) {
$this->job = $val;
return;
}
function getJob() {
return $this->job;
}
/* school methods */
function setSchool( $val ) {
$this->school = $val;
return;
}
function getSchool() {
return $this->school;
}
/* home town methods */
function setHomeTown( $val ) {
$this->homeTown = $val;
}
function getHomeTown() {
return $this->homeTown;
}
/* home state methods */
function setHomeState( $val ) {
$this->homeState = $val;
}
function getHomeState() {
return $this->homeState;
}
}
我一直的一套方法,如果我們想要改變的屬性,但現在的性能,建立了經由__construct前面。這就是說,我們通過我們的$ attribs數組對象的實例,這反過來又通過$ attribs的自動構造。優勢利用關聯數組為此目的,我們並不需要明確地規定所有的變量與方法。這是極其方便的時候將與MySQL PHP的數據,我們將盡快支付。但首先,我們需要學習一點方法的互動和對象分組。
法相互作用
在這一點上,我們的方法不互動。讓我們添加一個小功能,例如,我們充分狀態轉換的名字給適當的縮寫。
$attribs = array(
'name' => 'Kirupa',
'homeState' => 'Alabama'
);
$kirupa = new User( $attribs );
echo 'Name: '.$kirupa->getName().'<br />'; // Kirupa
echo 'Home State: '.$kirupa->getHomeState().'<br />'; // Alabama
echo 'State Abbr.: '.$kirupa->getHomeStateAbbr().'<br />'; // AL
class User {
private $name;
private $homeState;
function __construct( $attribs ) {
$this->name = $attribs['name'];
$this->homeState = $attribs['homeState'];
}
/* name methods */
function setName( $val ) {
$this->name = $val;
return;
}
function getName() {
return $this->name;
}
/* home state methods */
function setHomeState( $val ) {
$this->homeState = $val;
}
function getHomeState() {
return $this->homeState;
}
function getHomeStateAbbr() {
$abbr = States::$ABBRS[$this->getHomeState()];
if( $abbr ) {
return $abbr;
}
else {
return 'Unknown';
}
}
}
class States {
/* ideally this would be held in a database */
static $ABBRS = array (
'Alabama' => 'AL',
'Michigan' => 'MI',
'New York' => 'NY'
);
}
在這個例子中,我們充分利用國家的名字獲得相應的縮寫。我們這樣做是一類使用同一個靜態變量。靜態變量一般不會改變,可沒有辦法。這些變數的行為更多的參考和可用於像你的數據庫連接設置和其他網站廣泛的變數。靜態變量通常是命名與所有大寫字母。