Friday, 18 Jan 2008 7:00PM EST

PHP Classes Part 3: Static Keywords, Constants and the Scope Resolution Operator

From time to time in your PHP class adventures you may need to declare a variable as static or define a constant value. If you've ever used these objects in a language similar in syntax (i.e. C++), this should all be familiar, but if not, this tutorial will give you all the information to begin employing these important concepts. Those of you who are true PHP newbs, might want to check out the first 2 parts of this series; The Basics of PHP Classes and The Basics of PHP Abstract Classes.

Let's start by defining static varibles and constants. A constant is a value that you define in your class which must be equal to a constant expression. This means that you constant can be set to any string or number, but not to the value of a variable, the result of a function call or the result of a mathematical expression. The constant will be inherited by any and all instances of that class which you create. The static keyword, on the other hand, can be applied to any member or method of a class. These members and methods are no different than any other, except that they can be accessed without creating an instance of that class.

Defining a constant is simple. You precede the name of your constant with the const keyword and set it equal to whatever your constant value is. To access the value of your constant, you'll need to use the scope resolution operator (::) preceded by either self (from within the class) or the name of the class (from outside of the class).
<?php

class MyClass {
  const someconstant = 'value of my constant';

  public function printConst() {
    echo self::someconstant;
  }
}

// Print constant value without a class instance
echo MyClass::someconstant;

/*** In PHP5.3+ ***/
//Print constant value without a class instance while
//storing the class name in a variable
$className = "MyClass";
echo $className->printConst();

//Print constant value through an instance of the class
$classInstance = new MyClass();
$classInstance->printConst();
//or
echo $classInstance::someconstant;
?>
Static methods and members are different from constants in that the value of a static method or member does not have to remain static. In PHP, you are able to declare a static member which will be inherited by all instances of that class, but you are able to access and change that variable without an instance. Static methods work much the same way as static members, but methods can be accessed with or without an instantiated object. To declare a member or method as static, add the static keyword after the visibility keyword and before the member or method name. Much like constants, you will need to use the scope resolution operator (::) preceded by either self or the class name in order to access the member or method. You can also use the scope resolution operator preceded by parent to access the static member or method of a parent class.
<?php

class ParentClass {
    public static $staticVar = 'some value';

    public function returnStaticVal() {
        return self::$staticVar;
    }
}

class ChildClass extends ParentClass {
    public function returnStaticFromChild() {
        return parent::$staticVar;
    }
}

// Print static value without a class instance
print ParentClass::$my_static;

// Print static value with a class instance
$classInstance = new ParentClass();
print $classInstance->returnStaticVal();

//Print static value without a class instance while
//storing the class name in a variable
$className = 'ParentClass';
print $className::$staticVar;

// Print static value from a child class instance
print Childclass::$staticVar;
$childInstance = new ChildClass();
print $childInstance->returnStaticFromChild();

?>
That's all you'll need to get started using class constants and static class members and methods. As always, if you have a technique that you think is better or a tweak that improves on this code, please share it in the comments. If you have a tip, a trick or an idea for my next post, please don't hesitate to contact me.
Bookmark and Share

3 Comments So Far

Errors in code
Tuesday, 10 June 2008 5:27
$className = "MyClass";echo $classNmae->printConst() - ERROR1 - bad var name$classInstance->printConst();//orecho $classInstance::constant; - ERROR2  should be ::someconstant;
Errors in comment system
Tuesday, 10 June 2008 5:28
bar symbol is treated as comment end
Justin Spegele
Tuesday, 17 June 2008 7:26
@Errors
Thanks for pointing out the typos, they've been fixed. As for the comment system, well, it's far from perfect, but it's getting there...

Post a comment


If you are seeing this message, you are either using a screen reader or you have disabled CSS. Please do not fill in the following form field, titled "lastname", or your comment will not be saved. This field is only used to help prevent spam comments.


Welcome

JustinSpegele.com is where I share projects that I'm working on, php tutorials, web development tips and tricks, and random thoughts.

#MLS has a very odd notion of an all-star game. MLS all-stars vs. an EPL team? Still, should be very fun to watch. MLS 3 - Man United 2 1:41 PM Jul 28th from web
The New Digg And The Future Of Social News http://bit.ly/cM7Guq 10:44 AM Jun 29th from TweetMeme
so as of right now, the Big 10 has 12 teams and the Big 12 has 10 teams? http://sports.espn.go.com/ncaa/news/story?id=5276668 7:59 PM Jun 11th from web
heading to Las Vegas for #caworld in the morning 7:12 PM May 12th from web
Found out from CNN that I went to high school with a convicted terrorist who worked with Al-Qaeda. Not what I expected to see on the news 9:49 PM May 10th from web
View all posts on Twitter »

Friend me

Twitter Digg Facebook FriendFeed Del.icio.us iFanboy Last.fm Squidoo

Login

Username:

Password: