tags:

views:

300

answers:

4

How can I access function b from within function a?

This is what I have so far, and I'm getting this error: PHP Fatal error: Call to undefined method a::b()

class test {
 function a($x) {
   switch($x)
   {
    case 'a'://Do something unrelated to class test2
      break;
    case 'b':
      $this->b();       
      break;
   }
 }
}

class test2 extends test {
 function b() {
  echo 'This is what I need to access';
 }
}

$example=new test();
$example2=new test2();
$example->a(b);

For background information - function a is a switch for requests sent via AJAX. Depending on the request, it calls a function to add a record to a database, edit it etc.

Thanks!

+1  A: 

You cannot do this.

hsz
So the only way to do it would be to call $test2->b(); ?
Matt
Exacly - only that way.
hsz
$test2 is a 'test' and has access to methods a() and b();$test1 is a 'test' but not a 'test2' so only has access to method a()
thetaiko
also, $test1->a('b') will fail
thetaiko
+2  A: 

You can't, $test is not an instance of the test2 class, so it doesn't have method b. If you call $test2->a(b) instead, it could work, as long as you define b() in class test as well. That way the definition of b in class test2 overrides it.

Tesserex
+1  A: 

If your function can be called in static context, you can use

test2::b();

otherwise you'll need to do a

test2Obj = new test2();
test2Obj->b();

The following contains some appropriate documentation: http://us2.php.net/manual/en/language.oop5.paamayim-nekudotayim.php

Dominik
+4  A: 

You have to define an abstract method b in the base class test (which makes this class abstract, so you cannot have instances of it) to call this method, otherwise the function b is not defined in this class, only in it's subclass of which the base class knows nothing (and should not have to know anything).

Read up on inheritance.

Another thing: a and b are not defined, use quotes. (But this might be just lazyness in your example)

dbemerlin
Yeah, I left the quotes out for the example. Thanks for the answer!
Matt