PHP:OOP 和方法
我一直想知道如何在类中实现方法。 有人能解释一下如果以过程风格进行 OOP 意味着什么吗?
这是一个例子:
class Fld extends Model {
private $file;
private $properties = array();
public function init($file) {
$this->file = $file;
$this->parseFile();
}
private function parseFile() {
// parses the file
foreach($this->file as $line) {
//..................
}
$this->properties = $result;
}
}
我的意思是,拥有这样的方法来对类属性进行操作是一件好事吗?或者我应该将类属性作为方法参数传递... 我的意思是,如果不声明文件属性,这会导致错误。
I`ve been wondering how to implement methods in a class.
Could someone explain me what means if one does OOP in procedural style?
Here is an example:
class Fld extends Model {
private $file;
private $properties = array();
public function init($file) {
$this->file = $file;
$this->parseFile();
}
private function parseFile() {
// parses the file
foreach($this->file as $line) {
//..................
}
$this->properties = $result;
}
}
I mean is it a good thing to have methods like these that do operations for the class properties like that. Or should I pass the class property as method parameter...
I mean this would cause error if the file property wouldnt be declared.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果该文件对于您的对象是必需的,则它应该是构造函数中的参数。
当类中有一个不使用任何类属性的方法时,您应该考虑将该方法设为静态,甚至为此方法创建一个单独的类。
If the file is mandatory for you object, it should be a parameter in your constructor.
When there is a method in your class which does not use any of the class properties, you should think about making that method static or even create a separate class for this method.
我认为当类中的方法往往非常长且复杂时,人们将代码描述为“过程风格的 OOP”。
Martin Fowler 的《重构》一书将长方法描述为“代码味道”,暗示其部分代码可以分解为更小的方法或分离到其他类中。
请参阅:http://books.google.co.uk/books?id=1MsETFPD3I0C&lpg=PP1&dq=refactoring&pg=PA76#v=onepage&q&f=false
我认为你的代码完全没问题。只要记住该类的对象是多么一次性即可。一般来说,像这样的“解析服务”应该被创建、使用并丢弃。这样您就不必担心旧属性在重新使用时会造成混乱。
正如 eteubert 所建议的,在构造函数中传递工具有助于让客户端知道该对象是为了特定目的而创建的。
I think people describe code as "OOP in procedural style" when the methods inside a class tend to be very long and complex.
Martin Fowler's book 'Refactoring', describes a long method as a 'code smell' that hints that parts of its code could be broken down into smaller methods or separated out into other classes.
see: http://books.google.co.uk/books?id=1MsETFPD3I0C&lpg=PP1&dq=refactoring&pg=PA76#v=onepage&q&f=false
I think your code is perfectly fine. Just bare in mind how disposable the objects of the class are. Generally a 'parsing service' like this should be created, used and thrown away. Then you won't have to worry about old properties causing confusion if it is re-used.
As eteubert suggests, passing the tooling in the constructor helps to let the clients know that the object is being created for a very particular purpose.