Reputation: 1747
I'm reasonably green with OOP, and I can't quite intuit how composition and __autoload()
are supposed to work together. What I'm currently trying to build is a class which will have as it's properties quite a number of other classes. To give some context, this particular app lends support to an indie role-playing game that is being developed simultaneously.
The basic file structure goes:
localhost/project/
localhost/project/lib
localhost/project/lib/class
And so on. In index.php
I have:
<?php
require_once("lib/common.php");
// ...bunch of bootstrapping and what not...
$char = new Character;
?>
Then in common.php
:
<?php
define("DS", "/");
define("SER", "localhost");
define("BASE", "project");
define("LIB", "lib");
define("CLS", "class");
function __autoload($class_name) {
include CLS.DS.$class_name . ".php";
}
Finally, the main class, Character
, opens with:
<?php
class Character {
// properties
public $skills = new SkillSet;
public function character() {
//init
}
}
?>
When I run this, I get Parse error: syntax error, unexpected 'new' (T_NEW) in...
from Character, but I'm not clear on why. By the time the call to assign $char
is made, common.php
has been loaded, which means __autoload()
is available, and indeed it finds Character
.
My questions:
a) Why does __autoload()
not work inside a class, and
b) How is composition supposed to be done in object-oriented PHP?
Help most appreciated!
Upvotes: 0
Views: 228
Reputation: 70863
That syntax error has nothing to do with autoloading. You simply cannot create that class at this point in the code (this is not Java). You can only assign static values of scalars as the initial value of properties.
If you want that property to be initialized with another class, assign it inside the __construct()
function.
Regarding composition: Use depencency injection. Allow the outside world to pass the class to be used, instead of creating it inside that class.
Upvotes: 4