如何从父静态函数调用静态子函数? [英] How do I call a static child function from parent static function?

查看:120
本文介绍了如何从父静态函数调用静态子函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从父静态函数调用子函数?

How do I call child function from parent static function ?

在php5.3中,有一个名为get_called_class()的内置方法可以从父类调用子方法.但是我的服务器运行的是 php 5.1 .

In php5.3 there is a built in method called get_called_class() to call child method from parent class. But my server is running with php 5.1.

有什么办法可以做到这一点?

Is there any way can do this ?

我想从静态函数调用它.这样我就不能使用"$ this"

I want to call it from a static function . So that I can not use "$this"

所以我应该使用自我"关键字.

So i should use "self" keyword.

在下面的示例中,我的父类是"Test123",它试图从父类静态函数"myfunc"调用子类函数,例如"self :: test();"

Below example my parent class is "Test123" , from the parent class static function "myfunc" am trying to call child class function like this "self::test();"

abstract class Test123
{

  function __construct()
  {
    // some code here
  }

  public static function myfunc()
  {
    self::test();
  }

  abstract function test();
}

class Test123456 extends Test123
{
  function __construct()
  {
    parent::__construct();
  }

  function test()
  {
    echo "So you managed to call me !!";
  }

}

$fish = new Test123456();
$fish->test();
$fish->myfunc();

推荐答案

编辑:PHP 5.1无法实现您试图实现的目标.没有静态绑定 PHP手册 在PHP 5.1中,您需要显式命名子类以调用子函数:Test123456::test()self在类Test123 >(始终),并且static关键字不可用于在PHP 5.1中调用静态函数.

What you try to achieve is not possible with PHP 5.1. There is no late static bindings PHP Manual in PHP 5.1, you need to explicitly name the child class to call the child function: Test123456::test(), self will be Test123 in a static function of the class Test123 (always) and the static keyword is not available to call a static function in PHP 5.1.

相关: 新的自我与新的静态 等同于后期静态绑定(新静态)的PHP 5.2 ?

如果要引用静态父函数,则需要为php 5.1中的函数调用显式命名父(子)子.

If you are referring to a static parent function, then you need to explicitly name the parent (or child) for the function call in php 5.1:

parentClass::func();
Test123456::test();

在PHP 5.3中,您可以使用static关键字 PHP手册 来解析被调用类的名称:

In PHP 5.3 you can do this instead with the static keyword PHP Manual to resolve the called class' name:

static::func();
static::test();

如果这些不是静态的,则只需使用$this PHP手册 :

If those are non-static, just use $this PHP Manual:

$this->parentFunc();
$this->childFunc();

或者,如果名称相同,请使用parent PHP手册 :

Or if it has the same name, use parent PHP Manual:

parent::parentFunc();

(这与您要求的不完全相同,只是为了完整起见将其放在此处).

(which is not exactly what you asked for, just putting it here for completeness).

已针对非常特殊的情况(如后期静态绑定 PHP手册 .

Get_called_class() has been introduced for very specific cases like to late static bindings PHP Manual.

请参见对象继承 PHP手册 >

这篇关于如何从父静态函数调用静态子函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆