1

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
  • it was hard to write an answer that's easily understandable because you reuse your names a lot. I had to distinguish between the class test and the object test, and also you have a mysterious parameter called "b" passed to function "a", while also having a function called "b". For clarity sake you should use more descriptive and unique names in your examples. Commented Feb 18, 2010 at 15:57

4 Answers 4

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

1

You cannot do this.

3 Comments

So the only way to do it would be to call $test2->b(); ?
$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()
also, $test1->a('b') will fail
1

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: https://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.