Mahdi
Mahdi

Reputation: 9427

PHP abstract class constructor not working

I wish to access some of my variables in a way like this:

System->Config->URL

Which in this case 'System' is my core class, 'Config' is an array and 'URL' is an item inside the array. Here is my 'system.php' code:

<?php

abstract class System {

    public $Config;

    public function __construct() {

        $this->Config = (object) array('URL' => 'localhost');
    }
}

echo System->Config->URL;

?>

When I run the above code I just see this:

Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting ',' or ';'

Which is pointing out my echo line.

Now if I eliminate the abstract idea, and use this one, that works very well!

<?php

class System {

    public $Config;

    public function __construct() {

        $this->Config = (object) array('URL' => 'localhost');
    }
}

$System = new System();
echo $System->Config->URL;

?>

I've also tried to mix up the static and abstract keywords, but that didn't worked also. I even gave up with the __construct function and made a very normal method named 'Ready', but still couldn't call that when the class is defined abstract.

Does anyone knows what's wrong here? I have seen the similar codes works very well.

Any help or idea would highly appreciated!

Upvotes: 2

Views: 1871

Answers (2)

Nanne
Nanne

Reputation: 64429

I'm not sure what you are trying to do. The second example works because it is right. An abstract class is a class you need to extend, and then you can instantiate that (child) class just as in your working example.

You might need to read up on what "abstract" does.

Upvotes: 2

Bgi
Bgi

Reputation: 2494

Look at the definition of an "abstract" class. It's a class that cannot be instantiated. Only the classes that inherit it can be instantiated.

Upvotes: 4

Related Questions