简体   繁体   中英

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 )

Next code is how I am trying. Could you tell me what I am doing wrong?

Thank you in advance.

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

[...]

public function FreeLog($text)
{
    // echo $text . "\n"; #mistake
    $this->outputText .= text; #correct one
}

[...]

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

===========================================================================

EDIT

I made an error copying 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. As both files are in the same directory it should be "class_log.php" not "./classes/class_log.php" . There is no need for it anyway, as when you include them both in main.php it is loaded already. So try it without the require_once .

EDIT: As discussed in chat do it like this:

in main.php :

$Class_TestingLog = New Class_TestingLog($Class_Log); 

in 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 .

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