[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 126
  • Last Modified:

Have question about static modifier in OOP Code. Please see enclosed example code.

I cannot for the life of me understand why the following values are submit to 3.  I thought that the whole point of an extended class was to retain individual values independent of the parent class.  Furthermore, why aren't they all 1 instead of all being three 3?  Is this part of the quirkiness that leads developers to say PHP is too weird and idiosyncratic for its own good (and eventually leads to abandoning ship for other languages like Python)?

  class One {
    static $foo;
  }
  class Two extends One { }
  class Three extends One { }
  
  One::$foo = 1;
  Two::$foo = 2;
  Three::$foo = 3;
 echo One::$foo;   // 3
  echo Two::$foo;   // 3
  echo Three::$foo; // 3

Open in new window

0
LB1234
Asked:
LB1234
  • 3
  • 2
1 Solution
 
Ray PaseurCommented:
Class Two and Three assume the static property of Class One.  They do not redefine or override it in any way.
0
 
LB1234Author Commented:
Hi Ray, ok so this behavior only applies to static modifiers, not regular attributes?  And so since 3 was set last, all child classes get that value?
0
 
Ray PaseurCommented:
Yes.  Here is the reference on "Static."
http://php.net/manual/en/language.oop5.static.php

The terminology may be a little off-putting in PHP object-oriented notation.  The variables inside an object are called properties.  The functions defined in the class are called methods.

Class One has one property and no methods.  Class Two and Class Three have no properties of their own and no methods.
0
 
LB1234Author Commented:
Thanks again, Ray!
0
 
Ray PaseurCommented:
Glad to help.  One day soon, I promise, you'll come to love the PHP OOP model.  It's not perfect, but it's so much better than procedural code, that you'll never go back!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now