classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

classes

Post 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?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: classes

Post 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;
?>
(#10850)
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: classes

Post 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?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: classes

Post 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.
(#10850)
Post Reply