Re: Include and extending classes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux