Do objects receive and return values?
My book has asked the question: "What is the difference between objects and functions?"
The answer key says that functions are sets of statements referenced by name that receive and return values. It says that objects may have multip开发者_运维问答le functions, called methods; and multiple variables, called properties; all combined in a single unit.
Unfortunately, the book doesn't say whether or not objects receive and return values.... So, do they? I'm trying to find an example.
Yes, an object can be set up to be callable.
class Foo
{
public function __invoke($arg)
{
echo "$arg\n";
}
}
$f = new Foo(); // calls the __construct method if it exists
$f("Hello, World"); // calls the __invoke method.
But not all languages support such a concept, and it's not the norm.
I took a look at some of the other questions you have asked recently. Note that you cannot do this:
Foo();
That does not make any sense since Foo
is a class in this example.
Keep in mind that the term "object" refers to a specific instance (e.g., new Foo()
) of a "class."
An object's methods are functions and, for the most part, work just like regular functions. The differences are that methods have different visibilities and have access to their object's properties without having to have them passed in.
精彩评论