syntax? how to declare a member of a class which is itself a class

syntax? how to declare a member of a class which is itself a class

am 23.08.2007 17:06:28 von D_a_n_i_e_l

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
}

Re: syntax? how to declare a member of a class which is itself aclass

am 23.08.2007 17:15:54 von Joe Scylla

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
> }
>

class cB
{
private $a;
public function __construct()
{
$this->a = new cA();
}
}
$cb = new cB();
print_r($cb);



Returns:
cB Object
(
[a:private] =>
[cA] => cA Object
(
[blah:private] =>
)

)


Joe

Re: syntax? how to declare a member of a class which is itself a class

am 23.08.2007 17:17:09 von zeldorblat

On Aug 23, 11:06 am, 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
>
> }

Class members don't have a type specified. They'll take on the type
of whatever you put in them -- so there's no need to declare it
explicitly (nor is there syntax to do so).

Re: syntax? how to declare a member of a class which is itself a class

am 23.08.2007 17:31:05 von ELINTPimp

On Aug 23, 11:15 am, Joe Scylla 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
> > }
>
>
> class cB
> {
> private $a;
> public function __construct()
> {
> $this->a = new cA();
> }
> }
> $cb = new cB();
> print_r($cb);
>

>
> 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.