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

is this the same ?? (PHP)

i saw php syntax on the inetrnet like this

class foo {
      public static $cont = null;

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

I am wondering are those code "self::$cont" the same like "$this->cont" like this ??

class foo {
      public static $cont = null;

      if (null == $this->cont){
         //doing something here
  }
}

thanks :)

1 Answer

Maximillian Fox
PLUS
Maximillian Fox
Courses Plus Student 9,236 Points

Hi there,

In short, nope, this is not the same because your second one is going to give you an error. The reason is due to the static keyword that has been included when declaring the property of the foo class.

In order to make the second example not throw an error, you would be required to remove the static keyword from the class before accessing the property with $this->

Essentially, a static property or method of a class is something you can access without actually creating an instance of a class first. For example, if we had this:

<?php
// This class foo uses a static property called $bar.
class foo{
   public static $bar = 'I am a static property!';
}

//To output $bar to the screen, we don't have to create an instance of the class first.
echo foo::$bar;
?>

Now let's look at how we would access $bar by removing the static keyword.

<?php
// This class foo uses a public property called $bar, but this time it's not static.
class foo{
   public $bar = 'I am NOT a static property!';
}

//To output $bar to the screen, we have to create an instance of the foo class first before we access the bar property.
$foo = new foo();

echo $foo->bar;
?>

I hope this helps, getting to grips with the public, static, private and protected terminology for OOP can take some accustoming to, but keep at it and you'll be away in no time! :)

Rifqi Fahmi
Rifqi Fahmi
23,164 Points

thanks, u da real MVP :D