【问题标题】:Instance child class in abstract static method抽象静态方法中的实例子类
【发布时间】:2021-01-10 21:21:05
【问题描述】:

我对 php 很陌生,我想从抽象父类的静态方法中实例化一个子类。是否可以在 php 中使用?

这是我的工作:

父类:

<?php

namespace App\views;


abstract class Views
{
    protected $template_name = '';

    abstract protected function Get();

    public static function as_view($target = null, $params = null) {
        // Here is this trick
        $create = function () {
            $cls = get_called_class();
            return new $$cls();
        };
        $instance = $create();
        $instance->Get();
    }

    public static function get_template() {
        return self::$template_name;
    }

}

儿童班:

<?php

namespace App\views;

use App\views\Views;

class HomeViews extends Views {
    protected $template_name = 'home.html';

    protected function Get() {
        echo self::get_template();
        dump($this);
    }
}

我想这样使用它:

<?php

use App\views\HomeView;

HomeView::as_view();

但是 php 抛出错误:

[Thu Sep 24 16:23:50 2020] 127.0.0.1:57001 [200]: / - Uncaught Error: Class name must be a valid object or a string in /Users/dev/PhpstormProjects/my_project/devel/src/views/Views.php:17
Stack trace:
#0 /Users/dev/PhpstormProjects/my_project/devel/src/views/Views.php(19): App\views\Views::App\views\{closure}()
#1 /Users/dev/PhpstormProjects/my_project/devel/public/index.php(9): App\views\Views::as_view()
#2 {main}

【问题讨论】:

    标签: php class inheritance


    【解决方案1】:

    首先$template_name 应该是static,如果你想从静态方法中使用它。

    您可以使用late static bindings 访问父类中的静态方法和字段:

    <?php
    
    abstract class Views
    {
        protected static $template_name = '';
    
        abstract protected function Get();
    
        public static function as_view($target = null, $params = null) {
           $instance = new static();
           $instance->Get();
        }
    
        public static function get_template() {
            return static::$template_name;
        }
    
    }
    class HomeViews extends Views {
        protected static $template_name = 'home.html';
    
        protected function Get() {
            echo self::get_template() . "\n";
            var_dump($this);
        }
    }
    
    HomeViews::as_view();
    /* outputs:
    home.html
    object(HomeViews)#1 (0) {
    }
    */
    
    
    

    【讨论】:

    • @MagnusEriksson 如果你使用static:: 那么它取决于类。
    • 太棒了,完美!谢谢兄弟!不知道 static() 可以用!!
    • 你成就了我的一天!我爱你!
    猜你喜欢
    • 2019-04-15
    • 2012-12-03
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2014-07-03
    • 2010-10-23
    相关资源
    最近更新 更多