Andrew Schmitt
Andrew Schmitt

Reputation: 31

Accessing object property from caller

I have a file that contains essentially a library of classes. I am logging errors from these classes using a separate logEngine class that is included in the file. I would like to pull a property from the class that calls these classes and store it along with the logged errors. To put it differently file A has a class that calls different classes from file B. File B's classes log errors from a class located in file C. I would like file B's classes to pull a property out of the instanced class in file A, and include it in the logging class from file C.

More visual:

File A: Storage -> File B: Class Library for file A (storage) -> File C: Logging Class for file B

I need a property from the calling object in file A to be stored using the logging class in file C from the objects from file B.

Help me stackoverflow, you're my only hope. If this is confusing I apologize. I'm not sure if this is even possible. I am trying to avoid having to rewrite any code.

Upvotes: 0

Views: 172

Answers (2)

Andrew Schmitt
Andrew Schmitt

Reputation: 31

I figured out the answer. You use bebug_backtrace(). In the example below class "b" has the property "store_name" with the value "san marino" and is calling class "a". Class "a" uses backtrace to get the property "store_name" and its value from its calling class, class "b".

<?php

class a {
private $property;
function __construct($value) {
$this->property = $value;
$btrace = debug_backtrace();
$store_name = $btrace[1]["object"]->store_name;
echo $store_name;
}
}

class b {
public $store_name = "san marino";
function __construct() {
$test = new a("Prueba");
}
}

$c = new b();

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77966

Pass the instance into the logger:

// Class A
$logger = new Logger($this);    
$logger->doSomething($someParams);


// Logger
function __construct($caller){
    $this->foo = $caller->getBar();
}

Upvotes: 0

Related Questions