SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Oct 2005
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Reflection: static method invocation (PHP5)

    I would like to know whether it's possible to do something like this:

    Code:
    class Base {
    
     static public function foo() {
      // Should return the name of the subclass the method has been invoked on
     }
    
    }
    
    class A extends Base {
    
    }
    
    class B extends Base {
    
    }
    
    var_dump( A::foo() ); // Should print "A"
    var_dump( B::foo() ); // Should print "B"
    Is Base::foo aware of the class on which the foo method has been invoked?
    Please note: I do not want to override the foo method in each subclass.

  2. #2
    SitePoint Member
    Join Date
    Oct 2005
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Has anybody an idea how to do this?

  3. #3
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    United Kingdom
    Posts
    208
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's not really possible. This was the reason why the Zend Framework Active Record implementation was removed. I believe it might be possible to get the subclass name using a stacktrace, but even then not overly reliable.

    You would think that
    PHP Code:
    ...
    public static function 
    foo()
    {
      return 
    get_class$this );

    should work but I don't think it does.

  4. #4
    Obey the Purebreed trib4lmaniac's Avatar
    Join Date
    Dec 2004
    Location
    Cornwall, UK
    Posts
    594
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I dont think it's possible if you call the method statically. If you create instances of your classes you can then do:
    PHP Code:
    class Base {

        public function 
    foo() {
            return 
    get_class($this);
        }

    }

    class 
    extends Base {
    }

    class 
    extends Base {
    }

    $a = new A();
    $b = new B();

    var_dump($a->foo());
    var_dump($b->foo()); 
    Edit:

    @Shrike: It does not work because you have invoked the base method statically, which means there is no instance of the object, which means that $this does not exist.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •