doujiang1001 2016-04-08 00:26
浏览 102
已采纳

在静态方法中创建当前类的对象 - PHP

I have some problems with my class Model and other classes so I made this simple example to explain my problem :

class person{

  public static $a = "welcome";

  public function __construct(){
                               }

  public static function getobject()
  {
      $v = new person();
      return $v;
  }

}

class student extends person{

  public static $b = "World";

}

$st = student:getobject();//this will return person object but I want student object

echo $st->$b; // There is an error here because the object is not student

So I want to know what to write instead $v = new person(); to get the object of the last inherited class.

  • 写回答

1条回答 默认 最新

  • drlnsli18864734 2016-04-08 00:29
    关注

    Use the late static binding's static keyword.

    public static function getobject()
    {
        $v = new static();
        return $v;
    }
    

    So, with student::getobject() you get an instance of student.

    To retrieve the static (but why?) $b propriety, you can do $st::$b, or simply student::$b.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?