我相信这对你们大多数人来说都是个愚蠢的问题。不过,我已经为这件事大发雷霆了好一阵子了。来自ASP.NET/C#,我现在正在尝试使用PHP。但是整个OOrintation给了我困难的时间。
我有以下代码:
<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_func',我得到的只是:
你好
clsB构造函数结束
输入try_this()函数
有人能发现这个问题吗?
谢谢你的进阶。
发布于 2012-02-02 13:49:34
你的问题在于:
$A = new clsA();在这里,您要将一个新的clsA对象分配给局部变量 $A。您要做的是将它分配给属性 $A。
$this->A = new clsA();发布于 2012-02-02 13:57:38
作为第一个答案,也可以将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/>";
?>https://stackoverflow.com/questions/9113402
复制相似问题