如何访问我班级中$ this-> myObject所代表的对象的公共属性/方法?

时间:2018-02-22 15:10:55

标签: php object types casting

我试图访问自定义对象的getter。我想将对象发送给构造函数params(我目前正在发送到build方法(但是

我的班级代表我想要显示其值的对象:

class User{ 
        private $id;
        private $name;
        private $email;  

     public function __construct(int $id, string $name, string $email) { 
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
     }

     public function getName(): string {
        return $this->name;
     }

     ... // the other getters
}

在我的页面中:

$myUser = new User(1, "toto", "toto@url.com");

$blockUser = new UserBlock($sqlConnection);
$blockUser->setUser($myUser);
$blockUser->build();

界面IBlock:

interface IBlock {
    function __construct($sqlConnection);
    function build();
}

UserBlock类:

class UserBlock implements IBlock {
    private $myUser;

    public function __construct($sqlConnection) {
       ...
    }

    public setUser($myUser) {
       $this->myUser = $myUser;
    }

    function build() {
       echo "Name = ".$this->myUser->getName(); // ERROR: Doesn't know the type of $this->myUser so can't access to getName method.

       $tempVarUser = $this->myUser;
       echo "Name = ".$tempVarUser->getName(); // ERROR: Doesn't know the type of $tempVarUser so can't access to getName method.
    }
}

使用我的代码结构,如何访问$this->myUser类中变量UserBlock所代表的对象User的属性和方法?

我必须删除接口的实现并将User对象作为参数发送到build方法(这里我的接口不允许)。 希望这很清楚。谢谢你的帮助。

0 个答案:

没有答案