如何在php中调用父类方法

前端之家收集整理的这篇文章主要介绍了如何在php中调用父类方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是工作代码,但我想知道不使用另一个对象(注释$foo)我如何使用$bar对象使用类Foo的printItem()方法.新的oop编程概念所以可能是一个弱的问题,但真的无法找到:(

我使用范围解析运算符来使用Foo类的printItem(),现在我的查询就是当我们可以使用这个功能时,创建对象有什么用?何时在适当的编码环境中使用范围解析运算符.

  1. <?PHP
  2.  
  3. class Foo
  4. {
  5. public function printItem($string)
  6. {
  7. echo "This is in class Foo ". $string ."<br />";
  8. }
  9.  
  10. public function printPHP()
  11. {
  12. echo "PHP is great "."<br />";
  13. }
  14. }
  15.  
  16. class Bar extends Foo
  17. {
  18. public function printItem($string)
  19. {
  20. echo "This is in class Bar ". $string ."<br />";
  21. }
  22. }
  23.  
  24. //$foo = new Foo;
  25. $bar = new Bar;
  26.  
  27. $bar->printPHP();
  28. $bar->printItem("Bar class object");
  29. //Foo::printItem("Mental Case");
将printItem定义为静态方法,您可以使用Foo :: printItem(“Mental Case”);
或者用子方法调用它:
  1. public function printItem($string)
  2. {
  3. parent::printItem($string);
  4. echo "This is in class Bar ". $string ."<br />";
  5. }

猜你在找的PHP相关文章