How to Invoke a Method on an Object in PHP 


               


How to Invoke an Object Method in PHP

php


In this article, we show how to invoke a method in a class on an object.

Say you've created a class that has a method or methods in it as well as objects in it.

How can you invoke those methods on those objects?

We'll show below how to invoke methods on objects in PHP.

Being that methods typically compose classes and objects are tailored to run methods, this is essential to know.

Let's say below we have animals class and we have a walk() method. This simulates that an animals walks.

To invoke a method such as this in PHP, the general format to do so is shown below.



So in the above code, we have create a function called walk() that echoes out, "I'm an animal and I walk".

We then create an instance (or object) of the animals class, $turtle.

We invoke the walk() method on this object or you can say that the object invokes this method.

Either way, the $turtle object performs the walk() method.

To invoke a method on an object, you simply call the object name followed by "->" and then call the method. Since it's a statement, you close it with a semicolon.

When you are dealing with objects in PHP, the "->" is almost always used to access that object, whether it's a property or to call a method. It's kind of the way of dealing with objects in PHP.

Remember that when you invoke the method, the method must have "()" with it. It will not work without the parentheses.

We show the full PHP code of how to invoke a method on an object.



So in the above code, we've created a class named animals. To create a class in PHP, all you have to do is use the keyword class followed by the name of the class.

We then create the walk() function which echoes out, "I'm an animal and I walk".

We then create an instance of the animals class, $turtle.

We then invoke this walk() method on the $turtle object using "->" in between the object and the method.

So it's rather simple to invoke methods on objects in PHP.

Of course, some methods take parameters if you've created that for your method. But it works in the same method. If a method takes parameters, it's called in the same way, only with the parameter(s) included.

Going back to the PHP code above, if it's run, this gives the following output shown below.

Actual PHP Output


I'm an animal and I walk.


HTML Comment Box is loading comments...