所以我是面向对象编程领域的新手,我目前正面临这个问题(代码中描述了所有内容):
<?php
class MyClass {
// Nothing important here
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction({$this->className} $object){
// So, here I obligatorily want an $object of
// dynamic type/class "$this->className"
// but it don't works like this...
}
}
$object = new MyClass;
$another_object = new MyAnotherClass('MyClass');
$another_object->problematicFunction($object);
?>
任何人都可以帮助我吗?
谢谢,Maxime(来自法国:对不起我的英语)
答案 0 :(得分:3)
您需要的是
public function problematicFunction($object) {
if ($object instanceof $this->className) {
// Do your stuff
} else {
throw new InvalidArgumentException("YOur error Message");
}
}
答案 1 :(得分:0)
试试这个
class MyClass {
// Nothing important here
public function test(){
echo 'Test MyClass';
}
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction($object){
if($object instanceof $this->className)
{
$object->test();
}
}
}
$object = new MyClass;
$another_object = new MyAnotherClass('MyClass');
$another_object->problematicFunction($object);
答案 2 :(得分:0)
这称为type hinting,你不想支持你想做的事。
如果所有这些动态类名都有共同之处(例如,它们是某些特性的不同实现),您可能希望定义一个基类(可能是抽象)类或接口,并将该共同祖先用作类型提示:< / p>
<?php
interface iDatabase{
public function __contruct($url, $username, $password);
public function execute($sql, $params);
public function close();
}
class MyClass implements iDatabase{
public function __contruct($url, $username, $password){
}
public function execute($sql, $params){
}
public function close(){
}
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction(iDatabase $object){
}
}
否则,只需将支票移至problematicFunction()
正文内,其他答案即可解释。