Connecting Tech Pros Worldwide Forums | Help | Site Map

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

D_a_n_i_e_l
Guest
 
Posts: n/a
#1: Aug 23 '07
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
}


Joe Scylla
Guest
 
Posts: n/a
#2: Aug 23 '07

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


D_a_n_i_e_l wrote:
Quote:
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
ZeldorBlat
Guest
 
Posts: n/a
#3: Aug 23 '07

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


On Aug 23, 11:06 am, D_a_n_i_e_l <danwgr...@gmail.comwrote:
Quote:
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).

ELINTPimp
Guest
 
Posts: n/a
#4: Aug 23 '07

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


On Aug 23, 11:15 am, Joe Scylla <joe.scy...@gmail.comwrote:
Quote:
D_a_n_i_e_l wrote:
Quote:
how to declare a member of a class which is itself an object?
>
Quote:
class cA
{
private $blah;
public function foo()
{
return $blah;
}
}
>
Quote:
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/languag...ators.type.php

that way, you can gracefully handle exceptions.

Closed Thread