Page 1 of 1

Call to a member function on a non-object

Posted: Mon Dec 04, 2006 6:04 pm
by rmccue
I am using the hit counter from http://www.phpclasses.org/browse/package/2387.html
In the page I am calling the actual counter I use the following (cut-down):

Code: Select all

<?php
require_once('hitscounter.php');
$myfile = new HitsCounter('some.exe');
	function pageContent(){
$myfile->printdownloadlink('Download TruckDismount Portable', false);
	}
?>
It comes up with the error
PHP Fatal error: Call to a member function printdownloadlink() on a non-object in blah.php
I am assuming this is due to the fact I am calling it from inside another function.
Please help,
Thanks

Posted: Mon Dec 04, 2006 6:07 pm
by Chris Corbyn
:arrow: Moved to PHP Code

You're trying to call the object's method from within a function even though you instantiate the object outside the function. Therefore the object does not exist. Either declare it global at the top of the function, or pass it as a parameter.

Posted: Mon Dec 04, 2006 6:25 pm
by rmccue
As in

Code: Select all

global $myfile;
?
Cause I already tried that.
Should I just make the object within pageContent()?

Posted: Mon Dec 04, 2006 6:29 pm
by Luke
You could pass it as an argument...

Code: Select all

<?php
require_once('hitscounter.php');
function pageContent($file)
{
    $file->printdownloadlink('Download TruckDismount Portable', false);
}
$myfile = new HitsCounter('some.exe');
pageContent($myfile);
?>

Posted: Mon Dec 04, 2006 6:49 pm
by rmccue
Thanks for your help guys.
I couldn't call it like that because pageContent() was called in a different file.
I fixed the problem by moving the $myfile line inside the function.

Posted: Mon Dec 04, 2006 6:56 pm
by RobertGonzalez
Which version of PHP are you using? If it is PHP5, you can pass the object to the function directly. If it is PHP4, you pass it be reference...

Code: Select all

<?php
require_once('hitscounter.php');
$myfile = new HitsCounter('some.exe');

// PHP5
pageContent($myfile);

//PHP4
pageContent(&$myfile);

// PHP5
function pageContent($obj) {
  $obj->printdownloadlink('Download TruckDismount Portable', false);
}

// PHP4
function pageContent(&$obj) {
  &$obj->printdownloadlink('Download TruckDismount Portable', false);
}
?>
I might be wrong on some of the PHP4 stuff inside the function (I haven't messed with PHP4 in a while), but you can kinda see the way things would work.