PHP类:父/子通信

时间:2010-05-03 21:21:26

标签: php class variables parent

我在使用PHP扩展类时遇到了一些麻烦。 谷歌搜索了一段时间。

 $a = new A();
 $a->one();

 $a->two();
 // something like this, or...

 class A {
  public $test1;

   public function one() {
    echo "this is A-one";

    $this->two();
    $parent->two();
    $parent->B->two();
    // ...how do i do something like this (prepare it for using in instance $a)?

   }
 }

 class B extends A {
   public $test2;

    public function two($test) {
     echo "this is B-two";

    }
 }

我对程序PHP很好。

4 个答案:

答案 0 :(得分:2)

无法做到。首先,A类是B类的父级,因此使用父级的东西就在列表之外。

对于没有父类的子类,有很多事情要做:

  • B类需要A才能工作
  • B级可以做一切可以加上更多
  • B类有权访问(只要允许访问)A类的所有数据

这些都不是反过来的,所以它们共同构成了你不能调用孩子的功能的原因。

答案 1 :(得分:2)

你的例子很好,但你在这里表现出一点混乱:

public function one() {
    echo "this is A-one";

    $this->two();
    $parent->two();
    $parent->B->two();
}

你想要的是我想的:

class A
{
    function one()
    {
        echo "A is running one\n";
        $this->two();
    }
    function two()
    {
        echo "A is running two\n";
    }

}

class B extends A
{
    function two()
    {
        echo "B is running two\n";
    }
}

然后你想要创建一个B类型的对象并调用函数“one”

$myB = new B();
$b->one();

这将输出

A is running one
B is running two

这是多态类行为的一个例子。超类将知道调用当前实例的函数版本“two”。这是PHP和大多数面向对象语言的标准功能。

注意,超类从不知道子类,你可以调用“two”方法并运行B版本的唯一原因是因为在父(A)类中定义了函数“two”。

答案 2 :(得分:0)

仔细阅读PHP手册的Object Inheritance section。是的,http://us2.php.net/oop中有很多信息,但它可以帮助您考虑OOP可以获得的信息。

答案 3 :(得分:0)

这是可以做的事情:

class A{
  public function methodOfA (){
    echo "this is a method of A (and therefore also of B)";
  }
}

class B extends A{
  public function methodOfB (){
    echo "this is a method of B";
    // you can do {$this->methodOfA ()} if you want because all of A is inherited by B
  }
}

$a = new A ();  // $a is an A
$a->methodOfA ();     // this is OK because $a is an A
// can't do {$a->methodOfB ()} because $a is not a B

$b = new B ();  // $b is a B, and it is also an A, because B extends A
$b->methodOfB (); // ok because $b is a B
$b->methodOfA (); // ok becuase $b is an A

当然,还有更多。 php手册中有一个很好的OOP部分(在artlung的回答中)。

相关问题