实例化对象失败(设计模式) [英] instantiating an object fails (design patterns)
问题描述
让我说我有一个类
类Thing
{
函数__construct($ string)
{
//用字符串初始化
}
}
让'比如传递一个无效的字符串来构造它。什么是
处理这个问题的适当方法?我知道在Java中我可能会抛出
异常,但我不知道有多少人真的在
PHP中使用异常。所以,我不想依赖它。
处理这类情况的适当方法是什么?我想b / b
想到两个选项
1.如果Thing不能为
,那么只返回null的ThingFactory实例化。
2.删除构造函数,只需要一个initThing($ string)方法
,当出现问题时返回false。
这里适合什么?
-
http://www.douglassdavis.com
lets say i have a class
class Thing
{
function __construct($string)
{
// initialize by string
}
}
Let''s say an invalid string is passed to construct it. What is the
appropriate way to handle this? I know in Java I would probably throw
an exception, but I don''t know how much people really use exceptions in
PHP right now. So, I don''t want to depend on it.
What would be the appropriate way to handle this type of situation? I
was thinking of two options
1. A ThingFactory that just returns null if the Thing couldn''t be
instantiated.
2. Remove the constructor and just have an initThing($string) method
that returns false when something goes wrong.
What would be appropriate here?
--
http://www.douglassdavis.com
推荐答案
string)
{
//用字符串初始化
}
}
让我们说传递一个无效的字符串来构造它。什么是
处理这个问题的适当方法?我知道在Java中我可能会抛出
异常,但我不知道有多少人真的在
PHP中使用异常。所以,我不想依赖它。
处理这类情况的适当方法是什么?我想b / b
想到两个选项
1.如果Thing不能为
,那么只返回null的ThingFactory实例化。
2.删除构造函数,只需要一个initThing(
string)
{
// initialize by string
}
}
Let''s say an invalid string is passed to construct it. What is the
appropriate way to handle this? I know in Java I would probably throw
an exception, but I don''t know how much people really use exceptions in
PHP right now. So, I don''t want to depend on it.
What would be the appropriate way to handle this type of situation? I
was thinking of two options
1. A ThingFactory that just returns null if the Thing couldn''t be
instantiated.
2. Remove the constructor and just have an initThing(
字符串)方法
返回false什么时候出错了。
这里适合什么?
-
http://www.douglassdavis.com
string) method
that returns false when something goes wrong.
What would be appropriate here?
--
http://www.douglassdavis.com
< a rel =nofollowhref =http://www.douglassdavis.comtarget =_ blank> www.douglassdavis.com 写道:
www.douglassdavis.com wrote:
班级事件
{
函数__construct(
lets say i have a class
class Thing
{
function __construct(
这篇关于实例化对象失败(设计模式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!