如何在父类中泛化通用功能?

时间:2018-08-01 17:55:04

标签: php laravel

我有两个班级“ A”和“ B”。 这两个类具有一些功能和一个通用功能,即“ toJson()”。

我创建了一个父类“ Json”,用于将一个类转换为json。

class Json
{
    public function toJSON() {
        return json_encode(get_object_vars($this));
    }
}

class A extends Json{

    private $a;
    function __construct($input = null) {
        $this->a = $input;
    }
    //getter & setter
}

class B extends Json{
    private $b;
    function __construct($input = null) {
        $this->b = $input;
    }
    //getter & setter
}


$a = new A("A")->json();
$b = new B("B")->json();

我希望两个类都转换为json。但是返回“ null”。

我已经将'toJSON()'添加到两个类中。其工作正常。

是否可以泛化'toJSON()'?

3 个答案:

答案 0 :(得分:3)

如果我们跳过您的语法错误,而只关注当前的问题,那么一切都归结为property visibility

您不能访问该类之外的私有属性,包括在处理继承时。您可以将属性$a$b更改为protected或public,以允许JSON类对其进行访问。

您可以在此处尝试使用私有:https://3v4l.org/Vhr9M

您可以在这里尝试使用受保护的:https://3v4l.org/9neiQ

答案 1 :(得分:2)

不好:请检查Davon答案以找出问题的根源。顺便说一句,这应该是公认的答案。


您正在呼叫json()而不是toJSON()(您如何声明)。除此之外,$a$b属性在执行get_object_vars()时不可访问,因为它们被声明为private。改为将它们更改为protected

class Json
{
    public function toJSON() {
        return json_encode(get_object_vars($this));
        // or this?:  return json_enconde($this->a);
    }
}

class A extends Json {

    protected $a;

    function __construct($input = null) {
        $this->a = $input;
    }

    //getter & setter
}

class B extends Json {
    protected $b;

    function __construct($input = null) {
        $this->b = $input;
    }

    //getter & setter

}

Luego cuando hagas:

$a = (new A("A"))->toJSON();
dd($a);
  

“ A”

$b = (new B("B"))->toJSON();
dd($b);
  

“ B”

答案 2 :(得分:0)

无法使用new A("A")->json();,您需要制作一个对象或直接调用包装在(new A("A"))->toJSON();之类的括号中。您有toJSON而不是json的方法。您应该使用类似的方法

<?php
class Json
{
    private $v;
    public function toJSON($c) {
        $this->v = $c;
        return json_encode(get_object_vars( $this));
    }
}

class A extends Json{

    private $a;
    function __construct($input = null) {
        $this->a = $input;
    }
    //getter & setter
}

class B extends Json{
    private $b;
    function __construct($input = null) {
        $this->b = $input;
    }
    //getter & setter
}


$a = (new A("A"))->toJSON([1,2,3]);
$b = (new B("B"))->toJSON([4,5,6]);
echo $a;
echo $b;
?>

Live Demo