Forum Moderators: coopster

Message Too Old, No Replies

which one to use and why?

         

PHPycho

10:56 am on Jul 3, 2007 (gmt 0)

10+ Year Member



Hello forums!
I am curious about some question which i am going to mention here.
we know the advantage of using getters and setters in OOP.
Let us consider the case:
[php]<?php
class className{
var prop1;
var prop2;
var prop3;

function className(){
// Empty constructor
}

function setProp1($prop1){
$this->prop1 = $prop1;
}
function getProp1(){
return $this->prop1;
}
function setProp2($prop2){
$this->prop2 = $prop2;
}
function getProp2(){
return $this->prop2;
}
function addProp12(){
$value = $this->prop1 + $this->prop2;
// Alt $value = $this->getProp1() + $this->getProp2();
return $value;
}
}

// Using Class
$classObj = new className();
$classObj->setProp1("x");
$classObj->setProp2("y");
echo $classObj->addprop12();
?>[/php]
My Question is very simple..
once the property is set using methods, for internal use in the class file
which one to use and why?
1> $value = $this->prop1 + $this->prop2;
2> $value = $this->getProp1() + $this->getProp2();

Thanks in advance to all of you.

coopster

11:28 am on Jul 3, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



for internal use in the class file

Within the class itself?
I would likely use the member (variable) directly as it incurs less overhead than running the method (function).

But outside the class, in a public script? I would go with option 2. Once you get to PHP5 you can start designing classes with member (variable) and method (function) visibility [php.net]. So once you define your class member as only to be used within the class you will already have the thought process down pat.

class className{ 
protected prop1;
protected prop2;
protected prop3;
...

You won't be able to access the variables directly, you will have to do it within the script or use a public method.