6

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();

1

5 Answers 5

15

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

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

or

$var = bla_bla::boo();
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

3

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();

Comments

2

Short writing style:

$bla = (new bla_bla)->boo();

Comments

1
$bla = new bla_bla();
$var = $bla->boo();

1 Comment

but if I use new bla_bla(), wouldn't the class run other functions as well?

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.