如何設置和獲取屬性就像這樣。PHP - 設置並獲取方法
$newObj = new Core;
$newObj->setTitle("Value"); //where title is a property from the Core object
$newObj->getTitle();
即將到來的OOP請幫忙。
更新:有點像magento設置和獲取會話相同。
如何設置和獲取屬性就像這樣。PHP - 設置並獲取方法
$newObj = new Core;
$newObj->setTitle("Value"); //where title is a property from the Core object
$newObj->getTitle();
即將到來的OOP請幫忙。
更新:有點像magento設置和獲取會話相同。
PHP提供了所謂的魔術方法。你有一個__get
和一個__set
神奇的方法。
這使得可以訪問其他類不可訪問的屬性,雖然不通過setFoo()
和getFoo()
方法調用。如果你想這樣做,你必須爲每個屬性定義2種方法,或者你可以使用第三種魔術方法__call
。
您將獲得被稱爲第一個參數的方法的名稱以及其他參數的數組,以便您可以輕鬆地確定進行調用的操作。簡單例子:
public function __call($methodName, $methodParams)
{
$type = substr($methodName, 0, 3);
$property = lcfirst(substr($methodName, 3)); // lcfirst is only required if your properties begin with lower case letters
if (isset($this->{$property}) === false) {
// handle non-existing property
}
if ($type === "get") {
return $this->{$property};
} elseif ($type === "set") {
$this->{$property} = $methodParams[0];
return $this; // only if you wish to "link" several set calls.
} else {
// handle undefined type
}
}
謝謝你的魅力。 – MashiruAlexis
您可以使用簡單的公共方法將值設置爲class properties。
class Core {
private $title;
public function setTitle($val) {
$this->title = $val;
}
public function getTitle() {
return $this->title;
}
}
在setter中'return $ this'不是一個好習慣嗎? – akasummer
謝謝你,但我已經知道這種方法。當他們從產品檢索屬性時,我想像magento一樣做。 – MashiruAlexis
你需要一個簡單的類來做到這一點。
<?php
class Core
{
private $title;
public function setTitle($val)
{
$this->title = $val;
}
public function getTitle()
{
return $this->title;
}
}
$newObj = new Core;
$newObj->setTitle("Value");
$newObj->getTitle();
?>
謝謝你的快速回復,但我已經知道這種方法。當他們從產品檢索屬性時,我想像magento一樣做。 – MashiruAlexis
首先創建你的類像這樣
<?php
class sampleclass {
private $firstField;
public function getfirst() {
return $this->firstField;
}
public function setfirst($value) {
$this->firstField = $value;
}
}
?>
後,您可以通過生成的類的對象,並調用適當的方法使用這些方法。
調用該方法是這樣的,
$obj = new sampleclass();
$obj->setfirst('value');
echo $obj->getFirst();
那它。
你能澄清是什麼問題? – akasummer
你能詳細說明什麼使得magento方法特別嗎?就目前而言,這個問題似乎是關於基本制定者和獲得者。 – k0pernikus