Jump to content

Class Properties


snivek

Recommended Posts

Can you access class properties directly by calling the property name or do you have to create a method to return it?
[code]
<?php
Class Veggy {
    var $color;

    Function Veggy($color) {
          $this->$color = $color
    }

    Function get_color(){
          return $this->$color;
    }
}

$spinach = new Veggy("green")
print $spinach->$color;  /* will that work? */
print $spinach->get_color();  /*this shoulwork */
?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/33048-class-properties/
Share on other sites

In PHP4 all member data are public, that is, they can be viewed and mutated directly.  In PHP 5 you can make member data public, private, or protected.  Private and proteected member data can only be viewed and mutated via public methods (when not within the context of the class or a subclass).

PHP4 - these will both work.
[code]
<?php
Class Veggy {
    var $color;

    Function Veggy($color) {
          $this->$color = $color
    }

    Function get_color(){
          return $this->$color;
    }
}

$spinach = new Veggy("green")
print $spinach->$color;  /* will that work? */
print $spinach->get_color();  /*this shoulwork */
?>
[/code]

PHP5 - only the latter will work as expected

[code]
<?php
Class Veggy {
    protected $color;

    public function __construct($color) {
          $this->$color = $color
    }

    public function get_color(){
          return $this->$color;
    }
}

$spinach = new Veggy("green")
print $spinach->$color;  /* will that work?  No*/
print $spinach->get_color();  /*this shoulwork, and it does. */
?>
[/code]

Best,

Patrick
Link to comment
https://forums.phpfreaks.com/topic/33048-class-properties/#findComment-153982
Share on other sites

Does the following work if the variable is marked Public?
[code]
<?php
Class Veggy {
    public $color;  #marked public

    public function __construct($color) {
          $this->$color = $color
    }

    public function get_color(){
          return $this->$color;
    }
}

$spinach = new Veggy("green")
print $spinach->$color;  /* DOES THIS WORK NOW?  If not, what
is the point in a PUBLIC var if I still have to use a public method
to read/write it?*/

?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/33048-class-properties/#findComment-153986
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.