Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get set properties in php

Tags:

php

set

get

I'm from the C# environment and I'm starting to learn PHP in school. I'm used to set my properties in C# like this.

public int ID { get; set; } 

What's the equivalent to this in php?

Thanks.

like image 979
Jeppe Strøm Avatar asked Feb 16 '12 22:02

Jeppe Strøm


People also ask

What is get and set method in PHP?

Getters and setters are methods used to define or retrieve the values of variables, normally private ones. Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object.

What is __ get in PHP?

__get() is utilized for reading data from inaccessible properties.

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

What is $this in PHP with example?

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.


1 Answers

There is none, although there are some proposals for implementing that in future versions. For now you unfortunately need to declare all getters and setters by hand.

private $ID;  public function setID($ID) {   $this->ID = $ID; }  public function getID() {   return $this->ID; } 

for some magic (PHP likes magic), you can look up __set and __get magic methods.

Example

class MyClass {    private $ID;    private function setID($ID) {     $this->ID = $ID;   }    private function getID() {     return $this->ID;   }     public function __set($name,$value) {     switch($name) { //this is kind of silly example, bt shows the idea       case 'ID':          return $this->setID($value);     }   }    public function __get($name) {     switch($name) {       case 'ID':          return $this->getID();     }   }  }   $object = new MyClass(); $object->ID = 'foo'; //setID('foo') will be called 
like image 52
Mchl Avatar answered Sep 19 '22 06:09

Mchl