简体   繁体   English

从调用者访问对象属性

[英]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. 我正在使用文件中包含的单独的logEngine类记录这些类的错误。 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. 换句话说,文件A具有一个与文件B调用不同类的类。文件B的类记录了文件C中一个类的错误。我希望文件B的类从文件A中的实例类中提取一个属性,并且将其包含在文件C的日志记录类中。

More visual: 更直观:

File A: Storage -> File B: Class Library for file A (storage) -> File C: Logging Class for file B 文件A:存储->文件B:文件A的类库(存储)->文件C:文件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. 我需要使用文件B中对象中文件C中的日志记录类来存储文件A中调用对象中的属性。

Help me stackoverflow, you're my only hope. 帮助我stackoverflow,您是我唯一的希望。 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(). 您使用bebug_backtrace()。 In the example below class "b" has the property "store_name" with the value "san marino" and is calling class "a". 在下面的示例中,类“ b”具有值为“ san marino”的属性“ store_name”,并且正在调用类“ a”。 Class "a" uses backtrace to get the property "store_name" and its value from its calling class, class "b". 类“ a”使用backtrace从其调用类“ b”中获取属性“ store_name”及其值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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