views:

108

answers:

4

I'm looking for a way to transparently run code when a class is defined - more importantly, when the class is extended.

For example, if I have:

class A
{  function define()
   {  echo "A has been defined!\n";
   }
   __magicDefine
   {  define();
   }
}

class B extends A
{
}

I'd like that to print "A has been defined!\n". Is this impossible?

+3  A: 

Is this impossible?

Yes.

Peter Bailey
+2  A: 

That would be impossible, yeah. Nothing gets called on class definition.

This concept is even sort of aggressively unsupported; try writing

class foo {
    static function __construct() {
        echo "hi!";
    }
}

and you'll get Fatal error: Constructor blah::__construct() cannot be static.

chaos
+1  A: 

I guess what you're trying to do is keep track of objects that are running? Not exactly sure what your end goal is here.

Perhaps you're looking for the ReflectionClass at run time? You can determine if a class exists and what the extended class is.

It also sounds like what you're aiming for is an object factory that keeps track of objects that are being used. Look up singletons, factory, and static member functions/variables concepts for those.

As for this:

class A 
{ 
 public function __construct()
 { print "A has been called";
 } 
}

if class B overrides the constructor, it's not going to call A's constructor. Ex:

class B extends A
{
 public function __construct()
 { print "B has been called";
   // parent::__construct(); /// would print out A has been called
 }
}

However in code, you can check if B is an instance of A one of many ways:

function doSomethingWithA(A $a)....

function doSmoethingWithA($a)
{
 if($a instanceof A)
 {
  // blah
 }
}

Don't know if that helps much.

Daniel
That would actually be helpful if I wasn't already on that track. Thanks! I'm exploring other ways of doing what I need. I'm building a database abstraction layer called Sqool, and its really nice for the user to be able to just create a single class then use it. The problem is that I only know an underlying "sqool class" (table) exists if someone has already instantiated at least one object. The way i'm planning on solving this is having the user create a function (with a standard name) that I can call if i'm not yet aware of the class. If you're interested check out http://tinyurl.com/o3tz2n
B T
A: 

In Java, this is possible, by using a "java agent" which would register a java.lang.instrument.ClassFileTransformer with the JVM.

Rogerio