开发者

PHP - Access a function from another class

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!


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)


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.


You cannot do this.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜