PHP - Getters And Setters In Php
I'm having issues with getter and setter functions in PHP. Following is how I have written my PHP classes.
-------------------------------------------------------------------------------------------------------------------- File1.php -------------------------------------------------------------------------------------------------------------------- Code: [Select] <?php class TestClass1 { private $var; public function get_varvalue() { return $this->var; } public function set_varvalue($TestVar) { $this->var = $TestVar; } } ?> -------------------------------------------------------------------------------------------------------------------- File2.php -------------------------------------------------------------------------------------------------------------------- Code: [Select] <?php $obj = new TestClass1(); $obj->set_varvalue("someText"); ?> -------------------------------------------------------------------------------------------------------------------- File3.php -------------------------------------------------------------------------------------------------------------------- Code: [Select] <?php class TestClass2 { $obj2 = new TestClass1(); echo $obj2->get_varvalue(); } ?> File1, File2 and File 3 are separate PHP files. File2 uses the TestClass1 object to set the value to variable 'var' but when I try to get the value print the value in File3.php by creating an object for the same class and calling the get_varvalue() function, I'm getting a blank output. Please help me to solve this issue. Thank you. Regards, tab4trouble Similar TutorialsI know that magic __get and __set are invoked automatically when an object is instantiated, but what about stuff like getName() and setName() Code: [Select] class NameClass { private $_name; public function getName() { return $this->_name; } public function setName($value) { $this->_name = $value; } } $someName = new NameClass(); $someName->setName('Bob'); echo $someName->getName(); 1. Could the setName() and getName() just as easily be named something generic like: hotName() coldName() Code: [Select] class NameClass { private $_name; public function hotName() { return $this->_name; } public function coldName($value) { $this->_name = $value; } } $someName = new NameClass(); $someName->coldName('Bob'); echo $someName->hotName(); 2. Also, the setName() and getName() methods must be called manually, right? Unless they are manually called, they just sit there, do nothing, am I correct? Thanks |