views:

65

answers:

4
+2  Q: 

class constructor

I am trying to understand how classes and functions work more. So i have written a class with 2 functions inside it. Then initiated the class with

$fifaadmin = new FifaAdmin;

When I try to call this class from another page i get the following error

Call to a member function leagueToReplace() on a non-object

What am i doing wrong? Is there an obvious answer? Thanks

+2  A: 

You need to instantiate the class on each page. Each script is executed independently.

Will Vousden
+1  A: 

Sounds like $fifaadmin didn't instantiate the object correctly.

What does this say?

var_dump($fifaadmin instanceof FifaAdmin);

It should return true if it is set up correctly. Try it just before you call a method on it.

When you say another page, do you mean from a PHP include or a new URL (and therefore request)?

You will need to instantiate it on every request, as HTTP is stateless.

alex
Returns false! On another page, like an include file yeah.The fifaadmin is a class on a page called fifaadmin.php which is an include. When i say $fifaadmin->method1(); it should use that method.
Luke
Ensure that the class definition is included before you attempt to make an instance of the object.
alex
That is also true in the case you save an object of a custom class in the PHP session.
kiamlaluno
Hey, yeah I wasnt including the file!Fixed now. THanks
Luke
+1  A: 

Depending on what your code does, you might want to use static methods:

// common.php
class Common {
    public static function calculate($x, $y) {
        return $x + $y;
    }
}

// another PHP file: (you still need to include common.php
// you won't need to instantiate the class

echo Common::calculate(10, 20);
quantumSoup
+1  A: 

If you want to use an instance of class in different pages, you need to serialize it and save it somewhere (session is ok) and de-serialize it when you want use it.

More detail about serialize in PHP here http://php.net/manual/en/function.serialize.php

Duy Do