如何从另一个类方法获取方法


How get method from another class method

我有两个class

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

我不相信你能。可以让类B扩展Pet。这将允许您从类Pet调用函数。仔细阅读对象继承,这可能会有所帮助!http://php.net/manual/en/language.oop5.inheritance.php

您可以简单地在类B上扩展类Pet以调用来自Pet类的函数。因此类B继承了Pet的函数。

Class B extends Pet {
    // class B functions here...
}

当我在这里写下我的代码时,我笑了。

<?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!
?>

先生,你不能用->dog()调用$pet->setPet()->dog(),因为setPet()是一个函数而不是一个对象。就像他们说的,处理代码的正确方法是将其扩展为一个超类,并声明一个Dog类作为子类。

My variant

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