"Trying to get property of non-object" -Notice from require_once

"Trying to get property of non-object" -Notice from require_once

by Josh K. -
Number of replies: 3

I am trying to write an enrol plugin for moodle and therefor I need the functions of the /moodle/enrol/cohort/lib.php file.

But when I try..


global $CFG

require_once($CFG->dirroot . '../lib.php');


..then i get the following:

Notice: Trying to get property of non-object in /var/www/html/ moodle/....    on line 20


line 20 is..


require_once($CFG->dirroot . '../lib.php');


Don't really know what to do. I think the solution has to do with "dirroot".

Can someone help me?

Average of ratings: -
In reply to Josh K.

Re: "Trying to get property of non-object" -Notice from require_once

by lior gil -
Picture of Core developers

'$CFG->dirroot' returns the root directory where all your code files are.

'../' means one directory above the current.

Your path ($CFG->dirroot . '../lib.php') tells Moodle to look for lib.php in a directory above the root directory.

What you need to do is specify the exact path. Use this instead:

require_once($CFG->dirroot.'/enrol/cohort/lib.php');


Average of ratings: Useful (1)
In reply to Josh K.

Re: "Trying to get property of non-object" -Notice from require_once

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Looks like the file doesn't know what  $CFG is.

The first line of your PHP file should be one of the following:

require_once(dirname(__FILE__).'/../../config.php');

OR

defined('MOODLE_INTERNAL') || die();

The first is for files that a user is expected to directly visit via a URL, the second is for library files.

The first may need adjusting slightly, depending on how many subdirectories down from the root directory your code is located (i.e. add or remove some '/../' depending on the file's location).

If you missed out the 'config.php' include, then $CFG will be undefined.

Average of ratings: Useful (1)
In reply to Davo Smith

Re: "Trying to get property of non-object" -Notice from require_once

by Josh K. -
Thanks to both of you. It works nowsmile