You are here: Re: php classes calling functions using :: and -> « PHP Programming Language « IT news, forums, messages
Re: php classes calling functions using :: and ->

Posted by ZeldorBlat on 03/23/07 16:48

On Mar 23, 11:44 am, Rami Elomaa <rami.elo...@gmail.com> wrote:
> Anthony Smith kirjoitti:
>
>
>
> > I can call a class using "->", but it complains about the ::
> > I see on the net where :: is used. Is there a good explanation on when
> > to use one over the other or the differences?
>
> > $help = new help();
> > $help->foo();
> > $help::foo();
>
> > class help{
>
> > function foo(){
> > echo "test";
> > }
> > }
>
> :: is used for calling a method by class, not object. This is the part
> where php becomes rocket science. You can call a method of a class
> without having created an instance of the class eq. an object by calling
> it via the class.
>
> So if you have
>
> class help {
> function foo(){
> echo "Hello kitty!";
> }
>
> }
>
> You can call the method foo without creating an object:
> help::foo();
>
> Or you can create an instance of the class:
> $myhelp = new help();
>
> and then use the class pointer to call the method
> $myhelp->foo();
>
> Why use :: instead of -> then? hmm... I dunno, it's kewl? I've only used
> it once with a singleton where it seemed to make sense buy it's actually
> quite rare I think. People who work with objects big-time may have use
> for it, but I don't think it's actually all that necessary. It's good to
> have and good to know what it is and what it does, but on most days
> you'll be fine without it.
>
> --
> Rami.Elo...@gmail.com
> "Olemme apinoiden planeetalla."


It's really not all that rare -- in fact it's quite common.

As a matter of form, you should define class methods as static and
call them with :: If you get into the habit of calling your instance
methods with :: you can run into problems because $this is not
available (and PHP will complain accordingly). Furthermore there are
differences in inheritance between static methods and instance
methods -- namely that there is no inheritance with static methods --
but that provides you with a certain performance benefit.

The short answer (and it's certainly not the right one in all cases)
is that if you use $this in your method, make it an instance method
and call it with ->. If you don't use $this in your method, declare
it static and call it with ::

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация