Re: working with class inheritance

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

 



Jeff Taylor wrote:
> Hey all, got a slight problem, where for some reasons my variables dont seem
> to be getting stored in the child class:
> 
> e.g
> 
> class Parent
> {
>   $private type;
> 
>   public function __construct()
>   {
>   }
> 
>    public function GetType()
>    {
>       return $this->type;
>   }
> }
> 
> class Child implements Parent
> {
>     $public function __construct()
> 
> 
>       $this->type= 'Child';
>       }
> }
> 
> $Child= new Child();
> echo $Child->getType;
> 
> Can u see any reason why the type would return null?

Hi Jeff,

Aside from your obvious parse errors, the main problem is that you are
incorrectly using "private."  Since you wish to access $type from the
child class, you must use "protected" or declare a setter function as
Roman suggested.  However, setter functions are far less efficient than
simply using protected:

<?php
class whatever
{
    protected $type = 'whatever';
}

class Child extends whatever
{
    public function __construct() {$this->type='Child';}
}
?>

It should be noted that if you simply want to store the class name, a
better approach is to use get_class()

<?php
class whatever {}
class child {}
$a = new whatever;
$b = new child;
echo get_class($a), ' ', get_class($b);
?>

Of course, you may want to remove a prefix from the classname, in which
case you could also use a simple __get()/__set() declaration that
prevents accidental modification of object type:

<?php
class prefix_myclass
{
    function __get($var)
    {
        if ($var == 'type') return str_replace('prefix_', '',
get_class($this));
    }

    function __set($var, $value)
    {
        if ($var == 'type') return; // ignore
    }
}
class prefix_child extends prefix_myclass {}

$a = new prefix_myclass;
$b = new prefix_child;

echo $a->type , ' ' , $b->type;
$a->type = 5;
echo $a->type , ' ' , $b->type;
?>

Regards,
Greg
--
Experience the revolution, buy the PEAR Installer Manifesto
http://www.packtpub.com/book/PEAR-installer

-- 
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