Reputation: 741
I wonder if it is possible to call a method from another method inside the same class?
For exemple this code, very simple have a method method_foo()
which calls the method a()
:
<?php
class foo {
function a() {
return 3;
}
function method_foo() {
echo a();
}
}
$obj = new foo();
$obj->method_foo();
?>
But when I call method_foo()
, I'm receiving this error:
( ! ) Fatal error: Call to undefined function a() in /home/guest/public_html/... on line ... Call Stack
# Time Memory Function Location 1 0.0015 312032 {main}( ) ../index.html:0 2 0.0156 523056 foo->method_foo( ) ../index.html:1667
Why do I get this error? Can I make this example work?
Upvotes: 1
Views: 5375
Reputation: 1030
You can use $this
to call same class methods/variables
function method_foo()
{
echo $this->a();
}
Upvotes: 1
Reputation: 117
You should call method a() inside function method_foo() like this :
echo $this->a(); //this will output 3
You can read more about this at : http://php.net/manual/en/ref.classobj.php .
Upvotes: 1
Reputation: 481
You need yo use $this to access this method.
class foo {
function a()
{
return 3;
}
function __construct()
{
}
function method_foo()
{
echo $this->a();
}
}
$obj = new foo();
$obj->method_foo();
Upvotes: 3