我有两个班级
class Pet {
public $pet = null;
public function setPet(){}
public function getPet(){}
}
和
class B {
public $cat = 'cat';
public $dog = 'bog';
public function cat()
{
$pet = new Pet();
$pet->pet = $this->cat;
}
public function dog()
{
$pet = new Pet();
$pet->pet= $this->dog;
}
}
我可以得到这个:
$pet = new Pet();
$pet->setPet()->dog();
$pet->getPet(); //dog
答案 0 :(得分:0)
我不相信你可以。你可以让B级扩展Pet。这将允许您从类Pet调用函数。阅读对象继承,这可能会有所帮助! http://php.net/manual/en/language.oop5.inheritance.php
答案 1 :(得分:0)
您可以简单地在Class B上扩展Class Pet来调用Pet类中的函数。所以B类继承了Pet的功能。
Class B extends Pet {
// class B functions here...
}
答案 2 :(得分:0)
我在这里写下我的代码时笑了。
<?php
class Pet {
public $name;
public function setName($string) {
$this->name = $string;
}
public function getName() {
return $this->name;
}
}
class Dog extends Pet {
public function bark() {
echo "Arf arf!";
}
}
class Cat extends Pet {
public function meow() {
echo "Meoooww~ purrr~";
}
}
$dog = new Dog();
$dog->setName("Jacob");
$dog->bark(); //Arf arf!
echo "Good job, ".$dog->getName()."!"; //Good job, Jacob!
?>
先生你不能用$pet->setPet()->dog()
调用->dog()
,因为setPet()是一个函数而不是一个对象..就像他们说的那样,对你的代码做正确的事情是将它扩展为超类并将Dog Class声明为子类..
答案 3 :(得分:0)
我的变种
class Pet {
public $pet = null;
public function setPet($pet = null)
{
if (is_null($pet)) {
return new B($this);
} else {
$this->pet = $pet;
return $this;
}
}
public function getPet()
{
return $this->pet;
}
}
class B {
protected $pet = null;
protected $cat = 'cat';
protected $dog = 'bog';
public function __construct(Pet $pet)
{
$this->pet = $pet;
}
public function cat()
{
$this->pet->setPet($this->cat);
return $this->pet;
}
public function dog()
{
$this->pet->setPet($this->dog);
return $this->pet;
}
}
$pet = new Pet();
$pet->setPet()->cat();
var_dump($pet->getPet());