繁体   English   中英

从父类调用方法

[英]Call a method from parent class

我真的为这个问题疯狂。 我无法在子类的静态方法中从父类调用方法。

这是我尝试过的方法,但是不起作用。

class custom extends service {

    private $service;

    function __construct() {
        parent::__construct();
        $this->service = new service;
    }

   public static function activematches($callback) {

        $select_by_user = parent::$db->select('matches', '*', array('user_id' => $user_id, 

        if (count($select_by_user) == 0 && count($select_by_opponent) == 0)
            parent::$check->send('11');
        else
            $this->service->make($callback['request'], $callback['data']);
    }

当我调用$this->service我得到:

Fatal error: Using $this when not in object context

我尝试将其设置为静态,尝试通过调用父方法parent :: method将相同的方法放入子类中,但没有任何方法...

我是OOP的新手,有什么帮助吗?

为了在静态调用中进行访问,属性也必须定义为静态

 protected static $services;

从那里,您都需要在静态方法中进行引用。

 self::$services 

要么

 static::$services 

在这种情况下引用self将引用定义了引用的$ services属性。 static将从引用被引用的类上下文中引用属性。 有关更多信息,请参见手册中有关后期静态绑定的说明

更新

基于在这种情况下custom扩展service的事实,我怀疑这是您真正追求的。 像这样的类定义:

class custom extends service {
    public function activematches($callback, $user_id) {

        $select_by_user = $this->db->select('matches', '*', array('user_id' => $user_id)); 
        if (count($select_by_user) == 0 && count($select_by_opponent) == 0)
            $this->check->send('11');
        else
            $this->make($callback['request'], $callback['data']);
    }
}

可能更接近您想要的。

如果父方法的make不是静态的:您不能从子类的静态方法的父类中调用非静态方法。 您是否考虑过让子方法不是静态的? 我认为这是您的最佳选择。

如果父方法make是静态的:

parent::make($callback['request'], $callback['data']);

但这称为PHP 5.3.0中引入的Late Static Bindings 在旧版本中将无法使用,因此请务必小心。

致命错误:不在对象上下文中时使用$ this

这实际上是您的问题的答案。 静态成员的特定特性是-您可以在不创建对象的情况下使用它们。 $ this-对象的引用,在其中调用了上下文方法。

因此,尝试以这种方式查看问题-在静态成员中,您没有任何$ this。 您只能以这种方式使用父类的静态成员-self :: method。

或者,您实际上可以在父类上创建一个对象,并以“动态”表示法使用任何“动态”方法,但这会让您以后更加疯狂,相信我)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM