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.
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.
__get() is utilized for reading data from inaccessible properties.
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!
$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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With