|
Posted by ELINTPimp on 08/23/07 15:31
On Aug 23, 11:15 am, Joe Scylla <joe.scy...@gmail.com> wrote:
> D_a_n_i_e_l wrote:
> > how to declare a member of a class which is itself an object?
>
> > class cA
> > {
> > private $blah;
> > public function foo()
> > {
> > return $blah;
> > }
> > }
>
> > class cB
> > {
> > private cA $a; // I want this to be of type class A
> > }
>
> <code>
> class cB
> {
> private $a;
> public function __construct()
> {
> $this->a = new cA();
> }
> }
> $cb = new cB();
> print_r($cb);
> </code>
>
> Returns:
> cB Object
> (
> [a:private] =>
> [cA] => cA Object
> (
> [blah:private] =>
> )
>
> )
>
> Joe
Or, if you don't want to pass in the object:
class cB {
private $_cA; // object of class cA
public function setCA(cA $obj) {
$this->_cA = $obj;
}
}
placing the name of the class you are allowing to be passed to the
method ensures that it is the correct class. If not, a fatal error
occurs. You could, of course, do it with instanceof operator:
http://us3.php.net/manual/en/language.operators.type.php
that way, you can gracefully handle exceptions.
Navigation:
[Reply to this message]
|