2012-02-02 107 views
1

我相信这对大多数人来说看起来像是一个愚蠢的问题。然而,我一直在抨击我的头一阵子。 来自ASP.NET/C#,我试图现在使用PHP。但整个OOrintation给我很难。面向对象的调用方法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_func',我得到的是:

你好

clsB构造结束

进入try_this()函数

任何人都可以发现问题吗?

谢谢先进。

回答

9

你的问题就在这里:

$A = new clsA(); 

在这里,你要指定一个新的clsA对象到局部变量$A。你的意思做的是把它分配给财产$A

$this->A = new clsA(); 
1

作为第一个答案,但你也可以在B级延伸到一类这个方式,你可以在C访问类,像如下:

<?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/>"; 
    ?> 
+0

在这种情况下,他'could',但没有人知道,如果这是他想要做什么,因为也许A类无关,与分级结构:) – tim 2012-02-02 14:00:08

+1

@Alexandrew真正的B和C,但只是给它一个答案:-) – 2012-02-02 14:29:32

+0

是的,那就是我的意思。我知道它必须处理这样愚蠢的事情。有效。太感谢了。 – dsb 2012-02-02 14:45:12