2

所以我是面向对象编程领域的新手,我目前正面临这个问题(代码中描述了一切):

<?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);
?>

谁能帮我 ?

谢谢,马克西姆(来自法国:对不起我的英语)

4

3 回答 3

3

你需要的是

public function problematicFunction($object) {
    if ($object instanceof $this->className) {
        // Do your stuff
    } else {
        throw new InvalidArgumentException("YOur error Message");
    }
}
于 2013-02-25T10:53:44.977 回答
0

这称为类型提示,只是不支持您想要做的事情。

如果所有这些动态类名有一些共同点(例如,它们是某些功能的不同实现),您可能想要定义一个基(可能是抽象)类或接口,并使用该共同祖先作为类型提示:

<?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()正文内,正如其他答案所解释的那样。

于 2013-02-25T11:03:06.583 回答
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);
于 2013-02-25T10:54:52.557 回答