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[];
asked Nov 18, 2010 at 15:13
1
You can either access it directly or by instantiating the class:
$blah = new bla_bla[];
$var = $blah->boo[];
or
$var = bla_bla::boo[];
answered Nov 18, 2010 at 15:17
RDLRDL
7,7973 gold badges28 silver badges31 bronze badges
0
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.
answered Nov 18, 2010 at 15:16
PalantirPalantir
23.4k9 gold badges75 silver badges85 bronze badges
0
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[];
answered Nov 18, 2010 at 15:16
AlexVAlexV
22.2k16 gold badges86 silver badges119 bronze badges
Short writing style:
$bla = [new bla_bla]->boo[];
answered Jul 9, 2020 at 6:57
$bla = new bla_bla[];
$var = $bla->boo[];
answered Nov 18, 2010 at 15:15
enobrevenobrev
22k7 gold badges43 silver badges53 bronze badges
1
$bla = new bla_bla[]; $newbla = $bla->boo[];
answered Jun 2 at 22:12
1
PHP - Access Modifiers
Properties and methods can have access modifiers which control where they can be accessed.
There are three access modifiers:
-
public
- the property or method can be accessed from everywhere. This is default -
protected
- the property or method can be accessed within the class and by classes derived from that class -
private
- the property or method can ONLY be accessed within the class
In the following example we have added three different access modifiers to three properties [name, color, and weight]. Here, if you try to set the name property it will work fine [because the name property is public, and can be accessed from everywhere]. However, if you try to set the color or weight property it will result in a fatal error [because the color and weight property are protected and private]:
Example
In the next example we have added access modifiers to two functions. Here, if you try to call the set_color[] or the set_weight[] function it will result in a fatal error [because the two functions are considered protected and private], even if all the properties are public: