Page 1 of 1

SOLVED php object question

Posted: Fri May 02, 2008 12:02 pm
by yacahuma
lets say I want to uniquely identify each object class. Each one will have a mykey ID. In this example
parent::printmykey() will also print 2. I was expecting 1, but I guess as soon as the key is redefined in the child the parent value is lost. Is there a way to get 1 from the parent::printmykey() call?
(hint without redifining the printmykey function)

Code: Select all

 
class myparent
{
  var $mykey=1;
  
  function printmykey()
  {
    echo "PARENT KEY="  . $this->mykey;
  }
}
 
class child extends myparent
{
  var $mykey=2;
  
function printmykey()
{
    echo "CHILD DATA=" . $this->mykey;
}
function printparentkey()
{
     parent::printmykey();
}
  
  
}
$c = new child();
$c->printmykey();
$c->printparentkey();
 
 

Re: php object question

Posted: Fri May 02, 2008 1:12 pm
by EverLearning
Declare $mykey private in both classes.

Re: php object question

Posted: Fri May 02, 2008 1:29 pm
by Verminox
Everlearning: OP seems to be using PHP4, and private won't work.

Or since you are using this variable to identify a whole class and not individual objects, make the variable static.

Code: Select all

<?php
class myparent
{
  static $mykey=1;
 
  function printmykey()
  {
    echo "PARENT KEY="  . myparent::$mykey;
  }
}
 
class child extends myparent
{
  static $mykey=2;
 
function printmykey()
{
    echo "CHILD DATA=" . child::$mykey;
}
function printparentkey()
{
     parent::printmykey(); // or alternatively echo parent::$mykey
}
 
 
}
$c = new child();
$c->printmykey();
$c->printparentkey();
 
?>
Output:

Code: Select all

CHILD DATA=2 PARENT KEY=1
Note: Using the class name for scope resolution to access the static variable. Using keyword 'self' is a better option, but I don't think that is defined in PHP4. Switch to PHP5 if possible. Much better OOP support.

Re: php object question

Posted: Fri May 02, 2008 2:57 pm
by yacahuma
thank you. I am using php5. I had a small lapse in memory functions. forgot about the static. Maybe is time to take a break. :crazy:
Soon I will forget my own name

Re: SOLVED php object question

Posted: Thu May 08, 2008 2:51 pm
by yacahuma
Well the static did not work for what I wanted. I kept looking and found this

http://socket7.net/article/php-5-static-and-inheritance

So is not that the code is wrong is just php does not do what I thought it will do.


Thank you