Koobazaur Posted July 6, 2007 Share Posted July 6, 2007 Hi, I have a class that has a bool value like: $bDoSomething. I want to have functions to set/get that variable but I want to use the same function name for both. I tried the c way: public function something() { return $bDoSomething; } public function something($bToSet) { return $bDoSomething = $bToSet; } But I get an error that the something function is already declared. I tried this: public function something($bToSet) { if(isset($bToSet) $bDoSomething = $bToSet; return $bDoSomething; } And while it works, I get a warning whenever calling my function and not passing anything to it. What's the proper way of achieving waht I want here? Link to comment https://forums.phpfreaks.com/topic/58664-setretreive-class-functions/ Share on other sites More sharing options...
Daniel0 Posted July 6, 2007 Share Posted July 6, 2007 Overloading works a bit different in PHP, you can do something like this: <?php class Test { private $bDoSomething; public function __call($name, $arguments=array()) { if($name=='something') { if(count($arguments) == 0) // something() { return $this->bDoSomething; } else if(count($arguments) == 1) // something($bToSet) { $this->bDoSomething = $arguments[0]; return $this->bDoSomething; } else { trigger_error("Invalid argument count", E_USER_ERROR); } } } } $test = new Test(); $test->something("test"); echo $test->something(); // output: test ?> You could also choose to do it in another way (like you attempted): <?php class Test { private $bDoSomething; public function something($bToSet=null) { if(!empty($bToSet)) { $this->bDoSomething = $bToSet; } return $this->bDoSomething; } } $test = new Test(); $test->something("test"); echo $test->something(); // output: test ?> Note that overloading is for PHP5 only. Link to comment https://forums.phpfreaks.com/topic/58664-setretreive-class-functions/#findComment-291015 Share on other sites More sharing options...
Koobazaur Posted July 6, 2007 Author Share Posted July 6, 2007 Hmm... I think it'll be easier if I just leave those variables public and access them directly. Unless the encapsulation monkeys jump out at me and tear me to shreds >.> <.< Link to comment https://forums.phpfreaks.com/topic/58664-setretreive-class-functions/#findComment-291017 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.