了解PHP中的类 [英] Understanding Classes in PHP

查看:122
本文介绍了了解PHP中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正式迟到。 [让我解释一下]

I'm officially mentally retarded. [Let me explain]

我从来没有真正给过课程和他们的关系,直到今天。我试图找出似乎很明显的东西,但因为我很蠢,我看不到它。

I've never really given classes and their relationship any thought until today. I'm trying to figure out something that seems to be pretty obvious but since I'm stupid I can't see it.

让我们假设我有一个核心类将从不同的文件扩展。儿童类如何从其他兄弟姐妹调用函数(即如果这些被认为是孩子)。
示例代码:(不要杀我)

Let's say I have a Core Class that will be extended from different files. How can children classes call functions from other siblings (that is if those are considered childs at all). Sample Code: (don't kill me)

class cOne { 
    public function functionOne(){
       echo "something";
    }
}

然后在另一个文件中,我说:

Then on another file, I say:

class cOneChildOne extends cOne { 
    public function functionOne(){
       echo "something from child one";
    }
}

然而在另一个文件中我说:

And yet on another file I say:

class cOneChildTwo extends cOne { 
    public function functionOne(){
       echo "something from child two";
    }
}

如何创建一个新对象, when,这样我就可以以类似 $ newObject-> Children-> function(); I的方式从两个子类和父类访问函数认真考虑我今天完全失去了我的大脑,不能直接思考的选择。

How would I have to create a new object, and when, so that I'm able to access functions from both childs and the parent class in a fashion similar to $newObject->Children->function(); I'm seriously considering the option that I've completely lost my brain today and can't think straight.

我明显做错了,因为: $ newObject = new cOne; 创建对象,从一个子类无法访问任何不直接在核心类或本身的东西。

I've obviously doing something wrong since: $newObject = new cOne; creates the object but then the code from one of the subclasses is unable to access anything that's not directly in the core class or in itself.

这不像是非常重要或什么,但我想要了解这一点。
我做了很多阅读,不要误会,这就是为什么我认为自己迟到,而不只是懒惰。

It's not like it's vitally important or anything but I'd like to understand this. I've done a lot of reading don't get me wrong, that's why I consider myself retarded and not just lazy.

帮助我或射击我!感谢

推荐答案

您可以收集主类中的子实例static array

You can collect child instances in masters class static array

class C1{  
  static public $childs=array();
  function __construct(){
    self::$childs[]=$this;    
  }
}
class C1C1 extends C1{
  function hi(){
    echo 'hi from C1C1 <br />';
  }  
}
class C1C2 extends C1{
  function hi(){
    echo 'hi from C1C2 <br />';
  }    
}

$c1 = new C1C2();
$c2 = new C1C2();
$c3 = new C1C1();
$c4 = new C1C1();
$c5 = new C1C1();
$c6 = new C1C1();
foreach(C1::$childs as $c){
  $c->hi();
}

这篇关于了解PHP中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆