0

How to I get the object $this of that class where the current function was called from?

class a extends zebra {
  function xyz() {
     ...
     b::somestaticmethod();
  }
}

class b {
  public static function somestaticmethod() {
    $callerObj = get_called_class();
  }
}

The function get_called_class() fetches the name of the calling class in string format. What I am looking for is that, is there a way to get the object ($this) from the context of the calling class, just like what would have happened if $this was passed as an argument as below.

b::somestaticmethod($this);

Why?

I am planning to implement a polymorphic behavior on the somestaticmethod() method, which will check the calling class and based on the ancestor of that class guide the logic further.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • To clarify, you don't want just the class name but the actual object of the called class? – Script47 Jun 23 '18 at 22:02
  • Yup thats **exactly** what I am looking for. ....The whole object with all the inheritance and everything, without actually passing it as an argument. – Mohd Abdul Mujib Jun 23 '18 at 22:03
  • I'm not sure if such a thing exists however, why don't you just pass `$this` as a parameter? – Script47 Jun 23 '18 at 22:05
  • Yeah I have currently implemented it as you are suggesting, but then I was looking for a way to independently get the object without the need to pass the object, which (passing the object manually) doesn't give me a concrete guarantee that exactly `$this` was passed and not some other object. Just like the analogy of why use `get_called_class()` when you can just pass the class name from the calling class :) hope you get my point. – Mohd Abdul Mujib Jun 23 '18 at 22:08
  • This is the only other thing I could find: https://stackoverflow.com/questions/1093101/php-classes-get-access-to-the-calling-instance-from-the-called-method - and they all seem to be passing parameters from what I could tell from a quick glance. – Script47 Jun 23 '18 at 22:10
  • https://stackoverflow.com/questions/190421/caller-function-in-php-5 – Mr Glass Jun 23 '18 at 22:11
  • Thanks peeps, im gonna go through these resources real quick :) – Mohd Abdul Mujib Jun 23 '18 at 22:13
  • @MrGlass does that return the calling object? That is the key part of this question. – Script47 Jun 23 '18 at 22:13

1 Answers1

0

Reflection seems to work with inheritance and static class properties

<?php

class a {
  public static function x() {
    $callerObj = get_called_class();
    return new ReflectionClass($callerObj); 
  }
}

class b extends a {
    public static $y = [0, 1, 2];

    public static function z() {
        return parent::x()->getProperty('y')->getValue();
    }
}

print_r(b::z());
array_push(b::$y, 3);
print_r(b::z());
dcd018
  • 711
  • 5
  • 13