Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - access function from a class

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

like image 550
Alex Avatar asked Nov 18 '10 15:11

Alex


People also ask

How can we access public function from class in PHP?

Creating an instance of a class // creates an instance of the Html class $myPage = new Html; And then you can access all of the class's functionality — via your instance — using the familiar arrow, -> , syntax: // creates an instance of the Html class $myPage = new Html; // prints <p>Whoomp, there it is!

How do you access variables and methods from a class in PHP?

Your accessing a variable inside the class. Inside the class you call methods and variables like so: $this->myMethod() and $this->myVar . Outside the Class call the method and var like so $test->myMethod() and $test->myVar . Note that both methods and variables can be defined as Private or Public.

How do you call a function outside the class in PHP?

you can use require_once() with exact path of that class after that you should use the object of the included class and function name for calling the function of outer class. Save this answer.


3 Answers

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

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

or

$var = bla_bla::boo();
like image 154
RDL Avatar answered Sep 30 '22 19:09

RDL


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.

like image 40
Palantir Avatar answered Sep 30 '22 20:09

Palantir


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();
like image 25
AlexV Avatar answered Sep 30 '22 18:09

AlexV