Welcome to WebmasterWorld Guest from 107.22.55.73

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Class within a class

     
11:54 am on Jun 16, 2009 (gmt 0)

New User

5+ Year Member

joined:Apr 18, 2009
posts: 12
votes: 0

Is it possible to access a method of a class which is an object of a second class, from the second classes object.

that is
class a{
public method A
}

class b{
$vA = new a();
}

$vB = new b();

i want to access method A from $vB. How can i do this?

Thanks in advance

3:29 pm on June 16, 2009 (gmt 0)

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12541
votes: 1


Yes, as long as the properties and methods have the correct visibility.
$vB->vA->A();
3:10 am on June 17, 2009 (gmt 0)

New User

5+ Year Member

joined:Apr 18, 2009
posts: 12
votes: 0


Coopster, I cant seem to figure this out. Its generating an error. Here is my code please tel me if I've done something wrong

class super{
private $a = "Test";

public function getA(){
return $this->a;
}
}

class sub{
public $get = new super();
}

$obj = new sub();
echo ($obj->get->getA());

The error that is being displayed is

Parse error: syntax error, unexpected T_NEW in #*$! on line 11

12:46 pm on June 17, 2009 (gmt 0)

Administrator

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
posts:12541
votes: 1


A class property/member default value must be a constant expression, not (for example) a variable, a class member or a function call. See Example 3:
[php.net...]

So you need to do something like this:

class super { 
private $a = "Test";
public function getA(){
return $this->a;
}
}
class sub {
public $get;
public function __construct()
{
$this->get = new super();
}

}
$obj = new sub();
echo ($obj->get->getA());
8:03 am on June 18, 2009 (gmt 0)

New User

5+ Year Member

joined:Apr 18, 2009
posts: 12
votes: 0


Thanks mate...I get it now! Thanks