我认为我已经基本掌握了面向对象编程(OOP)/继承以及方法链的基础知识。然而,我仍然困惑于如何实际运用其中的一些内容。
我想做的事情是我之前在使用Magento时看到的一些操作: 在Magento中,我看到一种称为“选择器函数”的方法链被使用。很难用语言描述,但大致上是这样的:
$categoryName = Mage::getModel('catalog/category')->load($categoryId)->getName();
我对load($categoryId)
这部分很感兴趣,因为它是选择某个实例并允许我在该特定实例上运行函数的功能。
现在,我正在编写一个模块,使我能够在我们的网站上配置某些促销活动。由于我们将有许多不同的促销活动,并且我希望它们易于配置和修改,所以我想做类似的事情。
因此,如果我想要像这样做:
$prm = new Promotion();
$prm->addPromo('xmasPromo');
$prm->addPromo('nyPromo');
$prm->getPromo('xmasPromo')->setName('Promotion for Xmas!');
$prm->getPromo('nyPromo')->setName('Promotion for New Years!');
echo $prm->getPromo('xmasPromo')->getName(); // returns: Promotion for Xmas!
echo $prm->getPromo('nyPromo')->getName(); // returns: Promotion for New Years!
那个类的定义应该是什么样子的?
这可能比我预料的要简单或者复杂得多。无论哪种情况,非常感谢!
编辑: 所以,我根据deceze给我的信息进行了一些测试,但我仍然感到困惑。 除了糟糕的命名和在一个文件中放置两个类之外,这是我做的:
类文件:
class Promotion {
private $__arr = array();
public function addPromo($name) {
$this->__arr[$name] = new Promo();
}
public function getPromo($name) {
$this->__arr[$name];
}
}
class Promo {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $name;
}
}
and the run file:
require_once 'class.php';
error_reporting(E_ALL);
$prm = new Promotion();
$prm->addPromo('xmasPromo');
$prm->addPromo('nyPromo');
$prm->getPromo('xmasPromo')->setName('Promotion for Xmas!');
$prm->getPromo('nyPromo')->setName('Promotion for New Years!');
echo 'X: '.$prm->getPromo('xmasPromo')->getName(); // returns: Promotion for Xmas!
echo "\n";
echo 'N: '.$prm->getPromo('nyPromo')->getName(); // returns: Promotion for New Years!
This gives me Fatal error: Call to a member function setName() on a non-object in /var/www/test/index.php on line 11
.
But why? Shouldn't getPromo() give me back the object?
Thanks again..
Thanks to the great guys here, it works now. In case anyone were to pass by here with the same or a similar question, here's the final, working code:
Classes:
class Promotion {
private $__arr = array();
public function addPromo($name) {
$this->__arr[$name] = new Promo();
}
public function getPromo($name) {
return $this->__arr[$name];
}
}
class Promo {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
Test file:
require_once 'class.php';
error_reporting(E_ALL);
$prm = new Promotion();
$prm->addPromo('xmasPromo');
$prm->addPromo('nyPromo');
$prm->getPromo('xmasPromo')->setName('Promotion for Xmas!');
$prm->getPromo('nyPromo')->setName('Promotion for New Years!');
echo 'X: '.$prm->getPromo('xmasPromo')->getName(); // returns: Promotion for Xmas!
echo "\n";
echo 'N: '.$prm->getPromo('nyPromo')->getName(); // returns: Promotion for New Years!
getPromo
方法中返回PROMO
实例,像这样:return $this->__arr[$name];
。 - code-jaff