Jump to content

[SOLVED] The :: symbol.


Ninjakreborn

Recommended Posts

You use it to access class functions and members statically, where statically means you don't have an instance of the object.  However, you have to be careful how you use it.

 

If your class is designed correctly in the first place, you shouldn't be directly setting or reading the values of class properties (variables).  These should only be set and read through accessor functions.

For example:

<?php
  class a {
    public $property = null;
    // Rest of class follows...
  }

  $var = new a();
  // The next two lines of code are pretty bad practice IMO
  $a->property = "Hello, World!"
  echo $a->property;
?>

Realistically, the member $property should be private or protected and only settable / readable through methods (functions).

 

Now, let's change our definition of the class slightly above.

<?php
  class a {
    public static $static_value = null;
  }

  // We can access the static value like so
  a::$static_value = "Hi there!";
  echo a::$static_value;
?>

(edit) Doh!  PHP Does support consts! (/edit)

 

The same examples can be applied to functions within a class definition.  You can call a function within a class using the static syntax: my_class::my_function().

 

You have to be careful using this with class functions though; if the function uses the $this keyword it will not be defined and your code will crash.  The reason $this is not defined is simple:  $this refers to the instance of the class but you're calling the function without an instance, so there is no $this to refer to!

 

IMO, the best use of calling functions in this manner in PHP is to simulate namespaces, which is a  short way of saying it allows you to avoid naming collisions between functions that perform similar functions on different types of data.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.