Posts Tagged ‘PHP’
.NET Style Properties (Getters/Setters) in PHP
On any given day, I can be programming in one of many languages (C# .NET, PHP, JavaScript, CSS, & HTML [I know I may be pushing it calling CSS & HTML languages], and soon Visual Basic .NET because of a collaborative project). Don’t get me wrong, I love that part of my job. It keeps me sharp. Sure there is the occasional mishap where I forget that the . is the member accessor in the .NET languages, but it is the concatenation operator in PHP and I will throw the occasional $ into my C# code…
Another thing to know is that I am an object oriented programmer to the core…I am currently cleaning up after another developer who was not an object oriented guy…grr…there is data access code everywhere and he didn’t know the definition of object…finally I just took the functionality down because it was so bug ridden that whenever I would fix one bug, it would expose another. One thing that has constantly bugged me since I started coding in PHP that I didn’t like its method of using __get and __set for getters and setters (mainly because I still use a modified version of Hungarian notation, but that is a discussion for another blog post, so I didn’t like what the getters and setters would look like).
Then, tonight, as I was coding, I had an epiphany, I could use PHP’s optional operator syntax for a function to get something close to what I would want. So, where I would have coded this before:
1: <?php
2:
3: class Test {
4:
5: private $m_intId;
6:
7: public function setId($value) {
8:
9: $this->m_intId = $value;
10:
11: }
12:
13: public function getId() {
14:
15: return $this->m_intId();
16:
17: }
18:
19: }
20:
21: ?>
where I would do the following to access it $objTest->setId(1); or $intId = $objTest->getId(); (I would have to explicitly call the getter or setter)
Tonight I realized, I could code it this way:
1: <?php
2:
3: class Test {
4:
5: private $m_intId;
6:
7: public function Id($value = 0) {
8:
9: if($value != 0) {
10:
11: $this->m_intId = $value;
12:
13: } else {
14:
15: return $this->m_intId;
16:
17: }
18:
19: }
20:
21: ?>
Now, I can access the id by doing the following: $objTest->Id(5); or $intId = $objTest->Id();
What are your thoughts developers?
