[英]PHP - Call class function from another class
I am developing an app where I need to log the proccess. 我正在开发一个需要记录过程的应用程序。 So I was loggin from main.php and now I need to log from another class ( class_TestingLog.php )
所以我是从main.php登录的,现在我需要从另一个类( class_TestingLog.php )登录
Next code is how I am trying. 下一个代码是我正在尝试的方式。 Could you tell me what I am doing wrong?
你能告诉我我在做什么错吗?
Thank you in advance. 先感谢您。
main.php main.php
[...]
#Logging class
include_once("./classes/class_log.php");
$Class_Log = New Class_Log();
#TestingLog Class
include_once("./classes/class_testingLog.php");
$Class_TestingLog = New Class_TestingLog();
[...]
$Class_Log->FreeLog("Test log");
$Class_TestingLog->AnyFuncion();`
[...]
class_log.php class_log.php
[...]
public function FreeLog($text)
{
// echo $text . "\n"; #mistake
$this->outputText .= text; #correct one
}
[...]
class_testingLog.php class_testingLog.php
private $Class_Log = '';
[...]
public function __construct()
{
#Requires
require_once("./classes/class_log.php");
$this->Class_Log = New Class_Log();
}
public function AnyFuncion()
{
var_dump($this); #From real file
$this->Class_Log->FreeLog("Test log from another classs");
}
[...]
Browser output 浏览器输出
Test log
Browser output expected 浏览器预期输出
Test log
Test log from another classs
=========================================================================== ================================================== =========================
I made an error copying FreeLog(); 复制FreeLog()时出错; It stores the parameter string value into a private variable instead echo the variable.
它将参数字符串值存储到私有变量中,而不是回显该变量。
You require_once
statement inside __construct
for Class_TestingLog
is invalid and unnecessary. 您在
__construct
的Class_TestingLog
内的require_once
语句无效且不必要。 As both files are in the same directory it should be "class_log.php"
not "./classes/class_log.php"
. 由于两个文件都位于同一目录中,因此应为
"class_log.php"
而不是"./classes/class_log.php"
。 There is no need for it anyway, as when you include them both in main.php
it is loaded already. 无论如何都不需要它,因为当您将它们都包含在
main.php
它已经被加载。 So try it without the require_once
. 因此,在没有
require_once
情况下尝试。
EDIT: As discussed in chat do it like this: 编辑:如在聊天中讨论的那样做:
in main.php
: 在
main.php
:
$Class_TestingLog = New Class_TestingLog($Class_Log);
in class_testingLog.php
: 在
class_testingLog.php
:
public function __construct($ClassLog)
{
$this->Class_Log = $ClassLog;
}
This will use the same instance inside the Class_TestingLog
class as on the main.php
. 这将使用与
main.php
相同的Class_TestingLog
类内部的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.