LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Php Coding Question (https://www.linuxquestions.org/questions/programming-9/php-coding-question-484620/)

joelhop 09-18-2006 08:40 AM

Php Coding Question
 
I'm wondering if there is some way in php to return the name of the child class calling a method on a parent class?

Example:

<?php

Class parentObject
{
Public static Function returnClassName() {
return __CLASS__;

}

}

Class childObject extends parentObject
{

}

echo childObject::returnClassName();

?>

This returns parentObject, I would like it to return childObject as that is the child class that is actually invoking the method. I am wondering if there is a way to have the method return the name of the Class that invoked it, not the parent class it actually physically lives in?

Any help would be much appreciated!

Thanks,
KARL.

joelhop 09-18-2006 09:37 AM

I came up with this half working solution:

<?php

Class parentObject {

Static $ObjDegree = 3;

Public Function concreteReturnClassVariable() {
return get_class($this);
}

Public static Function staticreturnClassVariable() {
return get_class();
}

}

Class childObject extends parentObject {
Static $ObjDegree = 10;
}

$obj = new childObject();
echo $obj->concreteReturnClassVariable();

echo childObject::staticreturnClassVariable();

?>

I can get a method to return the name of the child class calling a method in the parent function if I use non-static functions after creating an instance of that child class and get_class($this).

However, it seems public static functions do not support get_class($this) so I can not do the same thing with a static call:

echo childObject::staticreturnClassVariable();

sundialsvcs 09-18-2006 03:17 PM

If you don't find an obvious language mechanism that lets you do something .. reconsider your design.

If you need to know "which child is calling my method" in order to make something work, it's a dead giveaway (imho) that something about the arrangement is wonked and you're creating code that you're going to regret.

(I've done it myself many times. "I wrote this?!" :eek: "Bad programmer! No biscuit!!" ) :D

joelhop 09-18-2006 03:25 PM

Yeah I agree the initial discussion that raised this question was about a hackish way to do something. I was just wondering if it was possible, but from what I've read it doesn't seem likely.


All times are GMT -5. The time now is 08:12 PM.