Jump to content

[SOLVED] Classes and Inheritance


chocopi

Recommended Posts

Is there anyway for two (or more) child classes to inherit a parent class with there only be one iteration of the parent class. What I mean is, if child class 1 changes one of the parent properties I would like child class 2 to have access to that variable. Obviously when you inherit the parent class a new object is created therefore causing both the child classes access to clones of the parent.

 

I know that i could global the parent object within each of the child methods, but seems like poor coding standards to me  :-[

 

I've had a quick check on google, php.net and these forums, but I'm not really sure what to search for :-\

 

I'm sure there is a very simple solution to this which I have overlooked

 

Any help will be greatly appreciated

 

ps. In case it matters I'm using php version 5.3.0

Link to comment
https://forums.phpfreaks.com/topic/181272-solved-classes-and-inheritance/
Share on other sites

static variables are shared between subclasses.

 

http://www.php.net/manual/en/language.oop5.static.php#89650

 

the example on the page

<?php
class MyParent {
    
    protected static $variable;
}

class Child1 extends MyParent {
    
    function set() {
        
        self::$variable = 2;
    }
}

class Child2 extends MyParent {
    
    function show() {
        
        echo(self::$variable);
    }
}

$c1 = new Child1();
$c1->set();
$c2 = new Child2();
$c2->show(); // prints 2
?>

Thanks for the replies.

 

I've just been a bit of testing with the static and your right  ;D

 

Once i re-read the static page and realised i needed to use

self::$var

instead of

$this->var

it became much simplier.

 

Edit:

 

Seeing how mikesta707 has replied while I was, i nearly missed it :D

 

I must remember to read the user notes on the php.net, sorry for wasting your time  :-[ That was laziness on my part

 

Anyways Thanks [ SOLVED ]

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.