Php 无法识别的静态方法-顺序是否重要?
我有错误Php 无法识别的静态方法-顺序是否重要?,php,oop,methods,static-methods,require-once,Php,Oop,Methods,Static Methods,Require Once,我有错误 调用未定义的方法异常::message() 在对象调用 Utils::message() (我正在捕获异常并替换为消息) 包含此对象的文件(require_once)与定义Utils的另一个文件一起包含在顶部文件中 所以我的问题是为什么Utils的方法不被认可。所有类都包含在主代码之前。包含顺序重要吗?还有其他提示吗 编辑。我的Utils类: class Utils { private static $count; private static $aggregateCo
调用未定义的方法异常::message()
在对象调用
Utils::message()
(我正在捕获异常并替换为消息)
包含此对象的文件(require_once
)与定义Utils
的另一个文件一起包含在顶部文件中
所以我的问题是为什么Utils
的方法不被认可。所有类都包含在主代码之前。包含顺序重要吗?还有其他提示吗
编辑。我的Utils
类:
class Utils {
private static $count;
private static $aggregateCount, $time, $last, $previous;
...
public static function message () {
echo "\n Count: ", self::$count++, " ";
$array = func_get_args();
foreach ($array as $entry) {
if (is_array($entry)) {
echo print_r($entry);
} else {
echo $entry;
}
}
}
...
}
类Utils{
私人静态$count;
私有静态$aggregateCount、$time、$last、$previous;
...
公共静态函数消息(){
echo“\n Count:,self:$Count++,”;
$array=func_get_args();
foreach($array作为$entry){
if(is_数组($entry)){
回音打印(输入);
}否则{
echo$输入;
}
}
}
...
}
下面是使用类的函数:
public function updateManyWithId ($schema, array $bundle) {
foreach ($bundle as $hash) {
$id = $hash[ID_KEY];
$hash = $this->_adjustId($schema, $hash);
try {
$this->update($schema, $id, $hash);
} catch (Exception $e) {
Utils::message("Cannot update hash: ", $hash, $e->message());
}
}
}
公共函数updateManyWithId($schema,array$bundle){
foreach($bundle作为$hash){
$id=$hash[id_KEY];
$hash=$this->\u adjustId($schema,$hash);
试一试{
$this->update($schema,$id,$hash);
}捕获(例外$e){
Utils::message(“无法更新哈希:,$hash,$e->message());
}
}
}
$e->message()
就是问题所在。它引用了一个名为Exception
的类,该类应该有一个名为message
的方法,但您的Exception
类没有该方法
查看异常的构造函数。当您抛出消息时,您正在传递消息,可能您正在查找$e->getMessage()
请看这里:
综上所述,考虑如下:
class Exception {
//construct is used when you throw new Exception (instantiate the class)
public function __construct($message) {
$this->message = $message; //now the object has a "message" property
}
//this is a "getter" for this object's message
public function getMessage() {
return $this->message; //return the message
}
}
请注意,getter/setters
的标准用法是使用getProperty
和setProperty
作为返回/设置该属性的方法名。请显示更多相关代码。但是当$this
引用您抛出的异常时,您似乎在使用$this
指针,而不是Utils
@m59请参见编辑。谢谢。谢谢,我现在将类简化为该函数,并包含了调用函数。@DmitriZaitsev没问题!顺便说一下,静态方法可能很危险,因为您使用的是Utils
explicity,而不是依赖注入。当创建使用Utils
的类时,应该像这样使用依赖项注入:$myObj=new myObj(new Utils())
,然后在myObj
的构造函数中,设置$this->Utils=$Utils
。然后在您的函数中:$this->Utils->message(…etc)
有很多理由认为这是最佳实践-研究依赖注入以获取更多信息!再次感谢,是的,除了这个类之外,我确实到处使用dep.injection:)我很难做出这个决定,但原因是Utils::message()
比$this->Utils->message()
更可读,后者太容易与$this->otherObject->otherMethod
混淆,所以这是一种提高可读性的方法。是的,这并不能使我的测试变得漂亮,但代码看起来更漂亮。我真的不知道什么是最好的