调用面向对象php中的方法


calling methods in object oriented php

我相信这对你们大多数人来说都是个愚蠢的问题。然而,我已经为此头疼了好长一段时间了。来自ASP.NET/C#,我现在正在尝试使用PHP。但整个印刷让我很难过。

我有以下代码:

<html>
<head>
</head>
<body>
<?php 
echo "hello<br/>";
class clsA
{
    function a_func()
    {
        echo "a_func() executed <br/>";
    }
}
abstract class clsB
{
    protected $A;
    
    function clsB()
    {
        $A = new clsA();
        echo "clsB constructor ended<br/>";
    }
} 

class clsC extends clsB
{
    function try_this()
    {
        echo "entered try_this() function <br/>";
        $this->A->a_func();
    }
}
$c = new clsC();
$c->try_this();
echo "end successfuly<br/>";
?>
</body>
</html>

据我所知,这段代码应该有以下几行:

你好

clsB构造函数结束

已输入try_this()函数

a_func()执行

然而,它不运行"a_foc",我得到的只是:

你好

clsB构造函数结束

已输入try_this()函数

有人能发现问题吗?

提前感谢。

您的问题就在这里:

$A = new clsA();

在这里,您将向局部变量$A分配一个新的clsA对象。您想做的是将其分配给属性$A:

$this->A = new clsA();

作为第一个答案,您也可以将b类扩展到a类,这样您就可以访问C中的a类,如下所示:

  <?php 
  echo "hello<br/>";
  class clsA{
      function a_func(){
          echo "a_func() executed <br/>";
      }
  }
  abstract class clsB extends clsA{
      function clsB(){
          echo "clsB constructor ended<br/>";
      }
  } 

  class clsC extends clsB{
      function try_this(){
          echo "entered try_this() function <br/>";
        self::a_func();
      }
  }
  $c = new clsC();
  $c->try_this();
  echo "end successfuly<br/>";
  ?>