Re: Include and extending classes

From: Date: Thu, 16 Jun 2005 16:48:36 +0000
Subject: Re: Include and extending classes
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-217082@lists.php.net to get a copy of this message
Mike Smith wrote:
I'm trying to consolidate code in a new project. My dirs are: / /inc
    core.class.php
/mods /mods/system
    system.class.php //extends core.class.php
    user.class.php //extends system.class.php
In core.class.php I have my generic special html methods and my db connection. I'm having trouble accessing $this->db (initialized in core.class.php) from user.class.php. Am I wrong in thinking user.class.php should be able to access methods/attributes of core.class.php?
http://php.net/manual/en/function.include.php So if user.class.php include()'s core.class.php then you should have the class definition (for methods) as well as any objects that were created. in core.class.php. In other words all variables get imported into the current scope in the calling file.
I'm running PHP 5.0.4 on Windows //core.class.php class core {
    var $db;
Is this actually var? Did you possibly call this private / protected? Var == Public, so the db property of any "core" class should be available.
    function core(){
    //initialize db connection (works from here)
    }
//Other methods } //system.class.php include "../../inc/core.class.php";
Note that relative paths can cause problems when you switch the current working directory. This likely isn't a problem for this particular issue you're having, but it's a gotcha for future work. What I do for relative includes is something like: include dirname(__FILE__) . "../../inc/core.class.php";
class system extends core {
    function system(){
/** See note below */ $this->core();
    }
} //user.class.php include "system.class.php"; class user extends system{
    function user(){
    //$this->db cannot be used here
What exactly do you mean by cannot be used... do you mean that you don't have access to db? Or perhaps you expect cascading __constructor calls which PHP does not do by default. Instead you need to call the parent constructor *explicitly*. $this->system();
    }
} TIA, Mike "There are no stupid questions." --my professors until I came into class.
-- NEW? | http://www.catb.org/~esr/faqs/smart-questions.html STFA | http://marc.theaimsgroup.com/?l=php-general&w=2 STFM | http://php.net/manual/en/index.php STFW | http://www.google.com/search?q=php

« previous php.general (#217082) next »