Coder Coder - 4 months ago 10
PHP Question

Can't instantiate class in different file PHP

I'm trying to instantiate a class which is located in a different file.

File A tries to instantiate the class located in File B:

require_once($CFG->dirroot . '/mod/assign/submission/example/classes/task/class.php');
// create the instance

$test = new testing();


Here is the class in File B to be instantiated:

<?php
namespace assignsubmission_example\task;


class testing extends \core\task\scheduled_task {
public function get_name() {
// Shown in admin screens
return 'example';
}

public function execute() {

echo "hello";

}
}
?>


But I get an error message:


Exception - Class 'testing' not found


Do you know what could be the issue?

Answer
$test = new assignsubmission_example\task\testing();

The only point where you don't have to specify the namespace is if you're in the same namespace of the class you're instantiating.