Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- -> or :: ?
July 13, 2004, 4:56 pm
rate this thread
I'm a bit confused with this and I hope you can help me:
I have a "Mother" class and a "child" that extends Mother.
The child's constructor should call Mother's constructor.
Now the question is:
How should child's constructor call mother's constructor?
I guess the second way is the right one, but I'm confused because:
1) both methods work;
2) both methods are in the manual;
can you help me to understand this (so I can sleep again ;-) )?
echo "I'm the Mother<br>\n";
class ChildA extends Mother
Mother::Mother(); // <--- is this correct? why?
echo "I'm the childA<br>\n";
class ChildB extends Mother
$this->Mother(); // <--- is this correct? why?
echo "I'm the childB<br>\n";
echo "$a->v: $a->v<br>\n";
echo "$b->v: $b->v<br>\n";
Re: -> or :: ?
You should understand OOP a bit more.
Using :: is invoking a class's method as static, i.e. directly from the
class; essentially, there is no difference between that and classic
user-defined functions, except that you can have several functions of the
same name and just call them using a different "prefix" (class name) in
The -> notation is used when you call a method, ie. a function attached to
an actual object.
In code, you use static method like this:
However, to call a method you need to have an object instantiated first:
$object = new YourClass();
The advantage of this is that the method is "attached" to the object, and
already "knows" everything about it. You can do the same by a static method
(or a classic function), but you would have to pass the object as a
This method thing might not seem like much, but this is just a facet of
OOP -- there is inheritance, with subclasses extending other classes, and
polymorphism, with same methods doing different things depending on their
object's class (so accelerate() does one for your generic Car class, and
something completely different for its Ferrari subclass) and so on.
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.
Re: -> or :: ?
Yeah, but calling the parent class constructor from a child's constructor
either way accomplishes the same - i.e. not a static function call, but a
method call that may change the values of the properties of the object
being instantiated. That's how I understood the OP's question. There is one
more way to get the same result in PHP4:
and, in fact, in PHP5, the "correct" way to call parent class constructor