但我不知道如何开始我的工作,并建立这个类。
您发布的代码不是一个类,而是一些伪装成OOP的过程代码。假设我创建Status
类型的对象:
$status = new Status();
这是一个对象?这个新对象的价值是什么?它看起来像一个对象,但它只是一些空的内存。没有数据,没有行为,只是无用的代码。
正确实现的类的构造函数构造对象,为使用做好准备。当构造函数返回时,该对象必须完全设置;应不需要$status->setId()
和$status->setName()
。
这是我建议您定义类:
class Status {
private $id;
private $name;
public function __construct($id, $name) {
// Validate arguments; an object must always be valid
if (! is_int($id) || $id <= 0) {
throw new InvalidArgumentException('$id must be a positive non-zero number.');
}
if (! is_string($name) || empty($name)) {
throw new InvalidArgumentException('$name must be a non-empty string.');
}
// The arguments are valid; go ahead and construct the object
$this->id = $id;
$this->name = $name;
}
}
现在让我们来创建一些Status
对象:
$pending = new Status(1, 'pending');
$confirmed = new Confirmed(2, 'confirmed');
根据您计划如何使用对象的属性,你可能不会将ID作为参数传递给构造函数,而是在内部生成它或使用固定的值列表。
或者你可以走一步,声明属性和Status
类为protected
构造并为$status
每个可能值创建一个子类:
class Status {
protected $id;
protected $name;
protected function __construct($id, $name) {
// ...
}
// ...
}
class Pending extends Status {
public function __construct() {
parent::__construct(1, 'pending');
}
}
class Confirmed extends Status {
public function __construct() {
parent::__construct(2, 'confirmed');
}
}
class Paid extends Status {
public function __construct() {
parent::__construct(3, 'paid');
}
}
的属性是protected
允许方法的儿童课程访问他们(当他们是private
只有类Status
看到他们的方法)。构造函数是protected
以防止创建Status
类型的对象,但允许子类(它们的构造函数实际)的方法调用它。 始终在子类的构造函数中调用父类的构造函数。
这样,当你需要创建一个表示状态的对象,所有你需要做的是:
$pending = new Pending();
$confirmed = new Confirmed();
// a.s.o.
不要急于添加“干将”(即访问方法对象属性并将其提供给您在代码中定义的客户端代码)。想想你想用存储在Status
对象中的值做什么,并检查该代码是否也可以保留在Status
类中。将特定于“未决”状态(f.e.)的代码放入Pending
类中,而不是Status
类中。
如果Status::$name
仅用于显示器,那么你最好实现__toString()
而不是getName()
:
class Status {
// ...
public function __toString()
{
// It is vital here to enforce the type of $this->name into the constructor
// __toString() must return a string
return $this->name;
}
}
这样,你的代码会显得好看:
$pending = new Pending();
echo('The status is: '.$pending);
// Output:
// The status is: pending
欢迎的StackOverflow!如果您遇到特定的编程问题,我们将很乐意为您提供帮助,但我们不在这里编写代码或为您设计系统。您至少需要尝试解决您自己的问题。请参阅[**我如何提出一个好问题?**](https://stackoverflow.com/help/how-to-ask)和[**我可以在这里询问什么主题?**](https ://stackoverflow.com/help/on-topic)。 –
我不明白你的问题到底是什么。你能否添加更多的细节? –
我无法破解这些状态背后的逻辑。如何正确书写它们以及这个课程应该如何工作。我的问题不仅包含语法不熟悉,而且还包含一个总体思路,如何构建这样的类。 @编辑 - >商店应该像这样工作 - >当用户添加项目到篮子,这些项目被标记为待定,等等。 我不知道我是否足够具体,如果没有,请告诉我。 – Phillip