Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Rifqi Fahmi
Rifqi Fahmi
23,164 Points

accessing static variable in PHP Object (OOP)

i saw a PHP OOP code on the internet like this :

<?php

class database {
    private static $cont = null;

    if(null == self::$cont){
         //Do something
    }
}

?>

The question is, are we need to use "self" keyword followed by this "Paamayim Nekudotayim" or Double colon in short in order to access the variable inside the object ??? Are we need to define a prefix in order to access variables inside PHP object beside private and static ??

thanks :D

2 Answers

Matthew Brock
Matthew Brock
16,791 Points

Yes you will, but you can only access from inside a function, if you are using it inside the class. The function can be static or not. If you are trying to use the variable outside of the class you call it by classname::$varname like

database::$cont;

Convention for php class name though is to have the first letter capitalized. class Database

Rifqi Fahmi
Rifqi Fahmi
23,164 Points

So is it right ??

<?php
class foo {
public $number = 2;
// I want to change the value of the number variable, so i Type
self::$number = 4;

}

?>
Rifqi Fahmi
Rifqi Fahmi
23,164 Points

thi is comment for above answer