简体   繁体   English

PHP-从另一个类访问函数

[英]PHP - Access a function from another class

How can I access function b from within function a? 如何从功能a中访问功能b

This is what I have so far, and I'm getting this error: PHP Fatal error: Call to undefined method a::b() 到目前为止,这是我得到的错误:PHP致命错误:调用未定义方法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. 对于背景信息-功能a是通过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). 您必须在基类测试中定义一个抽象方法b(使该类成为抽象的,因此您不能拥有它的实例)才能调用该方法,否则函数b不在该类中定义,仅在其子类中定义基类什么都不知道(也不应该什么都不知道)。

Read up on inheritance. 阅读继承。

Another thing: a and b are not defined, use quotes. 另一件事:a和b未定义,请使用引号。 (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. 您不能,$ test不是test2类的实例,因此它没有方法b。 If you call $test2->a(b) instead, it could work, as long as you define b() in class test as well. 如果您改为调用$ test2-> a(b),则只要您在类test中也定义了b(),它就可以工作。 That way the definition of b in class test2 overrides it. 这样,test2类中b的定义将覆盖它。

你不可以做这个。

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 以下内容包含一些适当的文档: http : //us2.php.net/manual/en/language.oop5.paamayim-nekudotayim.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM