Page 1 of 1

classes

Posted: Sat Apr 12, 2008 12:30 am
by SidewinderX
Why doesn't something like this work?

a.php

Code: Select all

 
<?php
 
class A
{
    public $untitled = "Hello World";
    
    function __construct()
    {
        require("b.php");   
    }
    
}
 
new A();
 
?>
 
b.php

Code: Select all

<?php
echo $untitled;
?>
I had expected it to say "Hello World" but it doesn't. Why?

Re: classes

Posted: Sat Apr 12, 2008 1:31 am
by Christopher
Programs, unlike people, always do exactly what you tell them to. It can be quite annoying.

$untitled is a local variable to the function __construct(). It is undefined in the example you posted. If you want to show the property of the same name, the code would be:

b.php

Code: Select all

<?php
echo $this->untitled;
?>

Re: classes

Posted: Sat Apr 12, 2008 1:24 pm
by SidewinderX
ok that makes sense. Now, I've worked with some CMS's and Frameworks, and when making extensions/modules to them, the extensions/modules have access to various classes in the API such as $db, without having to define/instantiate the class - it just has access to it. How does a structure like that work?

Re: classes

Posted: Sat Apr 12, 2008 1:42 pm
by Christopher
The object are probably instantiated by the framework/CMS before the point where you access them. Those objects are part of the structure.