扩展类php

时间:2016-01-12 21:53:41

标签: php class oop

如何获得A类的值扩展B类?

class A{
    private $a;

    public function setA($a){ $this->a = $a; }
    public function getA (){ return $this->a; }
}
class B extends A{

}

$a = new A();
$a->setA("Hello");

$b = new B(); 
echo($b->getA());    //empty

1 个答案:

答案 0 :(得分:0)

鉴于您似乎想要创建类B的实例,该实例维护现有类A实例的已填充值(而不仅仅是对它的引用),你想使用PHP的clone功能。

class A{
    private $a;

    public function setA($a){ $this->a = $a; }
    public function getA (){ return $this->a; }
}


class B extends A{
    //
}


$a = new A();
$a->setA("Hello");

$b = clone $a;

echo $b->getA();  // output is "Hello"