我开始为预定义的php包编写包装类。以下是课程:
class phpclass1
:: ping()
:: __construct(array $options)
:: clear()
:: addDoc(phpclass2 $string)
...
class phpclass2
:: __construct()
:: update()
...
以下是我为上述两个类编写的包装类:
class wrapper1 {
private $conn;
public function __construct(phpclass1 $object) {
$this->conn = $object;
}
public function add(wrapper2 $document) {
return $this->conn->addDoc($document);
}
}
class wrapper2 extends phpclass2 {
private $doc;
public function __construct() {
$this->doc = new phpclass2();
}
}
Here's how I'm using them:
$options = array (...);
$object = new phpclass1($options);
$conn = new wrapper1($object);
$doc = new wrapper2();
....
....
$conn->add($doc);
在我使用add
函数之前,一切正常。它给出了一个错误:Argument 1 passed to phpclass1::addDoc() must be an instance of phpclass2, instance of wrapper2 given
我错过了什么?我尝试了很多东西,但完全迷失了。
答案 0 :(得分:2)
您已定义
class phpclass1 :: addDoc(phpclass2 $string)
此方法期望参数是phpclass2的对象,但是您传递
return $this->conn->addDoc($document);
通过
$conn->add($doc);
和$ doc是wrapper2的对象而不是phpclass2
要修复添加新的公共方法
wrapper2::getDoc()
public function add(wrapper2 $document) {
return $this->conn->addDoc($document->getDoc());
}
答案 1 :(得分:2)
问题
您键入了一个wrapper1
方法,以便接受wrapper2
类型的所有优秀和良好。您声明的wrapper1
方法内部
public function add(wrapper2 $document) {
return $this->conn->addDoc($document);
}
其中$conn
被定义为phpclass1
个实例。当您致电
return $this->conn->addDoc($document);
期待某种类型的phpclass2
,但$ document文件实际上是wrapper2
类型,因为我们认为您无法编辑phpclass1
或phpclass2
您需要的文件修改你的包装类。
解决方案
解决方案1
更改wrapper2 to be
class wrapper2 {
private $doc;
public function __construct() {
$this->doc = new phpclass2();
}
public function GetDoc()
{
return $this->doc;
}
}
并使用如下
$conn->add($doc->GetDoc());
解决方案2
更改$ doc的签名;在wrapper2
到public
内,使用如下
$conn->add($doc->doc);
有关php中的typehinting的更多信息,请查看它的文档页面php type hinting
另外要考虑的另一件事是你是否需要/想要输入提示,而不是提出/反对的论据,因为它已经被讨论了很长时间,只是你可能想问的一个问题。如果答案是肯定的,您可能需要阅读以下link,其中讨论了使用类型提示的好方法和原因
我希望这会有所帮助
答案 2 :(得分:0)
您的phpclass1::addDoc
类型提示仅采用phpclass2
的对象。您的wrapper1::add
方法接受wrapper2
类型的对象,然后将其传递给phpclass1::addDoc
根据您的类,这是不一致的,因为wrapper2
不是phpclass2
的实例}。
您需要更改typehint或允许wrapper2
类提供它正在包装或扩展phpclass2
的{{1}}对象,以便它是wrapper2
的实例}
答案 3 :(得分:0)
将public function add(wrapper2 $document)
更改为public function add($document)
type hinting是问题所在。