nsj
nsj

Reputation: 45

How to get the name of the class from which a method call originates

How do you get the name of the class from which a method call originates. eg

Class Someclass{
 AnotherClass/methodname();
}


Class AnotherClass{
    function getNameOfOriginatingClass{
     //how do u achieve this?
      }
}

This question will help me solve this problem How to get the class from which a request originates in codeignitor please check it and help me solve it

how do i let AnotherClass know that the request is coming from Someclass?

Upvotes: 0

Views: 84

Answers (4)

Dharmang
Dharmang

Reputation: 3028

I don't know if this will be useful in case of CodeIgnitor as well, but in php there is a function called debug_backtrace() which can accomplish the task as follows:

class Animal {
    public function eat($food) {
        echo "Animal is eating : " . $food;
        $tree = new Tree();
        $tree->grow();
    }
}

class Tree {
    public function grow() {
        $bt = debug_backtrace();
        //var_dump($bt);
        echo "<br />";
        if (isset($bt[1]['object']))
            echo get_class($bt[1]['object']);
        echo "<br />Tree is growing";
    }
}

$animal = new Animal();
$animal->eat("Food");

Output:

Animal is eating : Food
Tree
Animal
Tree is growing

Upvotes: 0

Mohan
Mohan

Reputation: 4829

This will depend on your url but u can do something like this..

 function getNameOfOriginatingClass{
     $this->load->library('user_agent');
     $previous_url = $this->agent->referrer();
     $url_segments = explode($previous_url,'/');
     echo '<pre>';print_r($url_segments);    
 }

after printing this result u can see your link broken into parts in an array.. Normally the $url_segments[3] or $url_segments[4] will contain your previous function name and previous one will contain previous class name depending upon your url.

Upvotes: 1

hopsoo
hopsoo

Reputation: 305

You could also pass the caller as an argument

<?php

Class AnotherClass{

    public function getNameOfOriginatingClass($object){
        echo get_class($object);
    }
}

Class Someclass{

    public function __construct(){
        $A = new AnotherClass();
        $A->getNameOfOriginatingClass($this);
    }

}


$C = new Someclass();

Upvotes: 0

hopsoo
hopsoo

Reputation: 305

Do you mean to get the parent class name ? Use https://www.php.net/manual/en/function.get-parent-class.php But the parent class has to be extended by child.

Upvotes: 0

Related Questions