dsunj08246 2018-06-26 19:33
浏览 53
已采纳

too long

Is it possible to cast a parent class to its child in PHP? If not, what is the most efficient alternative to effecting this?

For example, the following results in an error:

<?php
class Foo {
    public $test;
    public static function create(): self {
        $a = new self();
        $a->test = 123;
        return $a;
    }
}

class Bar extends Foo {
    public $baz;
    public static function create(): self {
        $b = (self) parent::create(); // <--- Is this possible?
        $b->baz = 456;
        return $b;
    }
}

$bar = Bar::create();

var_dump($bar); /* should output:
  object(Bar)[35]
    public 'baz' => int 456
    public 'test' => int 123 */
  • 写回答

3条回答 默认 最新

  • doudong0425 2018-08-09 20:17
    关注

    I was able to implement this using the following strategy:

    class Foo {
        public $test;
        public static function create(array $row): self {
            $a = new static();
            $a->test = $row['Test'];
            return $a;
        }
    }
    
    class Bar extends Foo {
        public $baz;
        public static function create(array $row): Foo {
            $b = parent::create($row);
            $b->baz = $row['Baz'];
            return $b;
        }
    }
    
    $test = Bar::create([
        'Test' => 123,
        'Baz' => 456,
    ]);
    
    var_dump($test);
    /* Outputs:
        object(Bar)#2 (2) {
            ["baz"]=> int(456)
            ["test"]=> int(123)
        } */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动