PHP - access function from a class

2019-02-19 11:33发布

I have a class like:

class bla_bla extends WP_Widget {

  function boo(){
    return 'something';
  }

  ...
}

(it's a WordPress widget)

How can I access the boo() function from outside the class? I want to assign the value returned by that function to a variable, like $var = boo();

4条回答
祖国的老花朵
2楼-- · 2019-02-19 11:57

You can either access it directly or by instantiating the class:

$blah = new bla_bla();
$var = $blah->boo();

or

$var = bla_bla::boo();
查看更多
SAY GOODBYE
3楼-- · 2019-02-19 12:06

First you need an instance of the class. Then you call the method (if it's public). You should read some OOP tutorials as this is really basic stuff. See Object Oriented PHP for Beginners.

$bla = new bla_bla();
$var = $bla->boo();
查看更多
forever°为你锁心
4楼-- · 2019-02-19 12:16
$bla = new bla_bla();
$var = $bla->boo();
查看更多
在下西门庆
5楼-- · 2019-02-19 12:21

You must have an instance of that class to call it, for example:

$widget = new bla_bla();
$var = $widget->boo();

Otherwise, you can add the "static" keyword to the boo() function, and you could call it like $var = WP_Widget::boo(); but this changes the semantics and could break code.

查看更多
登录 后发表回答