Reputation: 97
I have 2 objects:
class a{
//some functions
}
class b{
function __construct(){
include('a.php');
}
}
Is this allowed in PHP? If not, Is there any optimized way to do this? Thanks!
Upvotes: 0
Views: 40
Reputation: 1
If your question is in regards to nesting a class in another, then no - you can not. However, as far as including files goes, it is possible to include a file with a class declaration from another class, as a little bit of testing would show you...
Upvotes: 0
Reputation: 1168
Your classes should be loaded at the beginning of your program, often using the built-in __autoload()
. If your $_SESSION contains classes, they'll need to be loaded before session_start()
. With that out of the way, the answer is Yes, one class can contain another, but No, not in the way you have defined. Consider the following:
class a{
//some functions
}
class b{
public a;
public anotherA;
public function __construct(){
$this->a = new a();
}
public function setAnotherA($anotherA){
$this->anotherA = $a;
}
}
You can pass a class to a function, or instantiate within a function of another class.
Upvotes: 1
Reputation: 1216
I'm not sure if I got what you want to do but try it like this:
class a {
public function sayA() {
echo "A";
}
}
class b extends a {
public function __construct() {
}
}
$test = new b();
$test -> sayA();
// > A
See also: http://www.php.net/manual/en/keyword.extends.php
Upvotes: 3