简体   繁体   中英

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.

Pass the instance into the logger:

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


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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM