Jump to content

cannot use extended class functions inside __construct.


creata.physics

Recommended Posts

Hi, I'm having a bit of a problem understanding why I'm not able to use the class I'm extending off of functions.

 

I have a category class that extends off my core class, inside that category class, I'm able to use the core functions and variables inside all custom functions, but not the __construct function.

 

So, to be clear, inside class class, I'm able to call $this->core->function() inside custom functions, such as function add_parent(), but not the __construct function.

 

Why is this happening, what is the logic behind this?

 

This is how I'm extending the class off of the core class:

<?php
$core  = new core;
$parent = new parents;
$parent->core =& $core;
?>

 

With this, like I said, I'm able to use all of my core functions inside all other classes called this way, so inside all of the other classes I can do:

<?php $this->core->function(); ?>

everywhere besides __construct().

 

Do I not have the class called properly? Do I need to pass my core class through differently? How can I fix this?

 

Thanks.

 

Extending a class in OOP has a very precise meaning, and that's not what you're doing here, so be careful with the terminology.

 

You shouldn't have to call a constructor twice. If you need to do something similar, you can do this:

 

class SomeClass {
    public function __construct() {
        $this->init();
    }

    public function init() {
        
    }
}

 

Then you can use init().

Well look at your code:

 

<?php
$core  = new core;
$parent = new parents;
$parent->core =& $core;
?>

 

The constructor is called when the object is instantiated here:

 

$parent = new parents;

 

But you're not assigning the core property until the next line:

 

$parent->core =& $core;

 

You can't access the methods of the object in the constructor because at that point core isn't a member of parent. One possible alternative is to pass $core into the constructor of $parent and assign it there before you use it, but it depends on what you're trying to accomplish.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.