Class problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bolven
Forum Newbie
Posts: 1
Joined: Thu Jul 29, 2010 6:54 pm

Class problem

Post by bolven »

Hello all,

I have a problem with a class (X) I want to execute one class (Z) function foo() bust I get an "Fatal error: Using $this when not in object contex" when I call it, any idea what's wrong or if this is possible.

I'll appreciate your help.

Thank you

Code: Select all

class Z {
   function foo() {
      // do somethig
   }
}


class X {
   $x
   
   function __contruct() {
	$this->x = new z(); 
   }

   function var() {
      $this->x->foo(); // Fatal error: Using $this when not in object contex
   }
}

// Class declaration here
class Y {
    function __contruct() {
        $z = new z();		
	$x = new x();
    }
}
Last edited by Benjamin on Thu Jul 29, 2010 7:22 pm, edited 1 time in total.
Reason: Added [syntax=php] tags.
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Class problem

Post by cpetercarter »

You need to make foo() a static method. You can then call it with classname::foo(). You can't use $this unless an object has been instantiated. Use self:: in your static method instead.
anilnakkani
Forum Newbie
Posts: 5
Joined: Wed Jul 21, 2010 2:16 am
Location: Hyderabad

Re: Class problem

Post by anilnakkani »

Hi, This is Anil,
Yes we can use Scope resolution operator can use ouside of class functions can call...

Example: ClassName::FunctionName();

Thanks
Anil.N
Thought Radius - Experts for Partners
Last edited by anilnakkani on Fri Jul 30, 2010 9:35 am, edited 2 times in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Class problem

Post by Christopher »

You need to create an object from the class:

Code: Select all

$z = new Z();
$z->foo();
(#10850)
Post Reply