Should I use a setter within a class to set a property? - php

I want to set a property value within my class. I can do it without a setter and a getter but I want to know the "correct" way to approach this. This is for a login script so the property and the setter are both private.
Should I just set the property directly or use a setter and a getter?

This is probably mainly a matter of personnal preference...
If you have to set the private property from a method of the class, I would say that you can access that property directly.
A reason to use an setter/getter, in that kind of situation, would be if you want to ensure that some condition or calculation is made on the data each time the property is set.
As a sidenote : of course, if your want to access your private property from outside the class, you'll have to use to public setter/getter -- but it doesn't seem to be what you are trying to do here.

This is a matter of opinion. Traditional object oriented programming principles say Yes, but it's really up to you.
Note that you will have to use a setter method if you set your property to private. Setters should always be public, so that other classes and methods can operate on the property. If you don't have any reason to access the property from outside your class though, then don't create a setter, because it really won't matter; you'll always have access to private member variables / properties from within the class.

Don't forget that you can use the "magic" __get / __set methods without having to create getters and setters for everything.
magic functions
edit: If the member variables are private or protected you will have to use a getter and setter. If they are public, it's a matter of style - though you should be consistent with the rest of your class.

Setter/Getters allow derived classes to modify/limit/enhance state and behavior of an object more easily. But you can over-do setters/getters and then they become a bit annoying. (Especially in languages that do not hide them).
class Foo {
protected $x;
public function __construct($x) {
$this->setX($x);
}
public function setX($x) {
$this->x = $x;
}
public function something($y) {
// not using a getter here, it's only an example
echo $this->x * $y;
}
}
class DoubleFoo extends Foo {
public function setX($x) {
parent::setX($x*2);
}
}
$df = new DoubleFoo(1);
$df->something(5);

Related

Passing variable to a static function inside subclass

I have a class with a variable $x that I want to use in a static function on his subclass.
class people{
protected $x;
function __constructor(){
$this->x = 'cool';
}
}
class person extended people {
function static status() {
'Here I want to use the x variable. I tried $this->x,parent::x..';
}
}
This obviously is not possible, since there is no object referred to inside a static method. That is the whole point of a static method: to be able to use it independent of an instantiated object. But without such object you obviously do not have a property $x...
There are a few alternatives, which one you chose depends on your situation:
you can hand over the value as an explicit argument (so static function status($x)), if you have access to the property of an instantiated object of class people.
you can declare the property as static const inside the class. In that case you obviously do have access from within a static class method. However it obviously is a constant that can be initialized, but which can not change its value over time.
you can design that property outside the class. Yes, this is obvious and changes the point of the class design. But since you already try to use a static method chances are that this method should not depend on any instantiated object at all...
In general one can say that the issue you ran into demonstrates that your class design is not conclusive, does not really make sense in itself in its current state. You will have to redesign the class (or maybe a bigger architecture).
Start by asking yourself a question: "why do you want to make the method status() static at all?"

PHP inheritance - methods and properties

I'm obviously not understanding inheritance correctly. I'll let my code do the talking:
abstract class Calc {
private $x;
private $y;
public function AddNumbers() {
echo $this->x. " + " .$this->y;
}
}
class myCalc extends Calc {
public function __construct ($x,$y) {
$this->x = $x;
$this->y = $y;
}
}
$calc1 = new myCalc(3,4);
$calc1->AddNumbers();
echo 'done';
exit;
OK, so what's going on here: I'd like to have an abstract class, that would define two properties (x and y) and an abstract method, (nevermind the concatenation of numbers, implementation of the method is out of the scope of my question) which would access there properties.
Then, a concrete class extends that abstract one. As you can see, I can successfully access the properties and set them, but when I call add numbers, it appears as if the properties are not set.
What is going on, why is this not working and how can I fix it?
I could just define a method for adding numbers in concrete class, but I want to have a method in abstract class with a definition that can be reused.
Thanks!
The two properties in the abstract class are private, which means they are NOT present and known in any class that extends this one.
So MyCalc does not write to these properties, and you cannot read them in the AddNumbers function. The MyCalc constructor actually creates new, public properties instead.
Make the properties "protected", and it will work.
The private keyword defines that only the methods in Calc can modify those variables. If you want methods in Calc and methods in any of its subclasses to access those variables, use the protected keyword instead.
You can access $this->x because PHP will let you create a member variable on the object without declaring it. When you do this the resulting member variable is implicitly declared public but it doesn't relate to the private variable defined in Calc, which is not in scope in myCalc.

PHP - Using one setter on all public properties of a class

There seems to be a lot of questions on setters and getters in PHP. However, none of them seem to mention that they do not work with public variables.
I have a series of public variables, which on setting need the same type of data checking (mainly strip_tags()).
What is the most code efficient way to do this whilst keeping the variables public?
The only option which seems to be available is creating a method 'setPropertyName' for all of my variables, which seems unnecessary to me.
Thanks for any help.
You can make them private, and using a public __set() and __get() to fetch the variables if they exists, and apply the validation/sanitation operations when they set.
For example:
class Foo {
private $variable;
private $otherVariable;
public function __get($key) {
return $this->$key;
}
public function __set($key, $value) {
$this->$key = strip_tags($value);
}
}
$foo = new Foo;
$foo->variable = "test"; //Works.
echo $foo->variable; //test
One thing you could try is the magic method __call($name,$args), then you wouldn't need to code the setPropertyName and getPropertyName functions:
function __call($name,$args){
$variable=lcfirst(substr($name,3));
if(!isset($this->$variable))
return false;
if(substr($name,0,3)=='set')
$this->$variable=$args[0];
else
return $this->$variable;
return true;
}
That being said, magic methods __get and __set work great with public variables if utilized properly. Below is how I utilize them:
public $variables=array();
function __get($name){
return isset($this->variables[$name])?$this->variables[$name]:false;
}
function __set($name,$value){
$this->variables[$name]=$value;
}
Then you can access them by using $this->name; rather than $this->getName();
Put both of them together and then you can do it however you want.
Again, this is a backbone. If you want to strip tags, you can put that in the code either in the setter or getter functions, or modify the call function to check for a 2nd argument that will strip the tags $this->setName($value,true);//strip tags
It is actually probably best practice to actually explicitly define your getters and setters. That being said you can use the __set() and __get() magic methods to provide common handling for requests to properties that are inaccessible from outside the class (protected and private).
So, all you would need to do is make your properties protected/private and specify __get() and __set() methods (also might need __isset() and __unset() as well if you will be checking the properties using isset() or trying to unset() properties).
Again, it is really best practice (IMO) to make all class properties inaccessible from outside the class and explicitly make setters/getters as need to provide access.

Get and set (private) property in PHP as in C# without using getter setter magic method overloading

Summary
Code sample:
Class People {
// private property.
private $name;
// other methods not shown for simplicity.
}
Straight forward. Let me assume that $name is a PRIVATE class member (or property, variable, field, call it as you wish). Is there any way to do these in PHP:
$someone = new People();
$someone->name = $value;
$somevar = $someone->name;
WITHOUT using __get($name) and __set($name, $value).
Background
I needed to check the assigned $value, therefore I simply need a getter setter like this:
getName();
setName($value);
And NOT necessarily a getter setter magic method overloading like this:
__get($value);
__set($value, $name);
That said, I simply need a getter setter. But that's NOT what I want. It just doesn't feel like object oriented, for people from static typed language such as C++ or C# might feel the same way as I do.
Is there any way to get and set a private property in PHP as in C# without using getter setter magic method overloading?
Update
Why Not Magic Method?
There are rumors floating around the web that magic method is 10x slower then explicit getter setter method, I haven't tested it yet, but it's a good thing to keep in mind. (Figured out that it's not that slow, just 2x slower, see the benchmark result below)
I have to stuff everything in one huge method if I use magic method rather then split them into different function for each property as in explicit getter setter. (This requirement might have been answered by ircmaxell)
Performance Overhead Benchmarking
I'm curious about performance overhead between using magic method and explicit getter setter, therefore I created my own benchmark for both method and hopefully it can be useful to anyone read this.
With magic method and method_exist:
(click here to see the code)
Getter costs 0.0004730224609375 second.
Setter costs 0.00014305114746094 second.
With explicit getter setter:
(click here to see the code)
Getter costs 0.00020718574523926 second.
Setter costs 7.9870223999023E-5 second (that's 0.00007xxx).
That said, both setter and getter with magic method and method exists justs costs 2x than the explicit getter setter. I think it's still acceptable to use it for a small and medium scale system.
Nope.
However what's wrong with using __get and __set that act as dynamic proxies to getName() and setName($val) respectively? Something like:
public function __get($name) {
if (method_exists($this, 'get'.$name)) {
$method = 'get' . $name;
return $this->$method();
} else {
throw new OutOfBoundsException('Member is not gettable');
}
}
That way you're not stuffing everything into one monster method, but you still can use $foo->bar = 'baz'; syntax with private/protected member variables...
ReflectionClass is your salvation
I know it's too late for Hendra but i'm sure it will be helpfull for many others.
In PHP core we have a class named ReflectionClass wich can manipulate everything in an object scope including visibility of properties and methods.
It is in my opinion one of the best classes ever in PHP.
Let me show an example:
If you have an object with a private property and u want to modify it from outside
$reflection = new ReflectionClass($objectOfYourClass);
$prop = $reflection->getProperty("PrivatePropertyName");
$prop->setAccessible(true);
$prop->setValue($objectOfYourClass, "SOME VALUE");
$varFoo = $prop->getValue();
This same thing you can do with methods eighter;
I hope i could help;
If using magical properties doesn't seem right then, as already pointed out by other posters, you can also consider ReflectionClass::getProperty and ReflectionProperty::setAccessible.
Or implement the necessary getter and setter methods on the class itself.
In response to the language features issue that you raised, I'd say that having a dynamically typed language differ from a statically typed one is expected. Every programming language that has OOP implements it somewhat differently: Object-Oriented Languages: A Comparison.
class conf_server
{
private $m_servidor="localhost";
private $m_usuario = "luis";
private $m_contrasena = "luis";
private $m_basededatos = "database";
public function getServer(){
return $this->m_servidor;
}
public function setServer($server){
$this->m_servidor=$server;
}
public function getUsuario(){
return $this->m_usuario;
}
public function setUsuario($user){
$this->m_usuario=$user;
}
public function getContrasena(){
return $this->m_contrasena;
}
public function setContrasena($password){
$this->m_contrasena=$password;
}
public function getBaseDatos(){
return $this->m_basededatos;
}
public function setBaseDatos($database){
$this->m_basededatos->$database;
}
}

PHP: What are Getter and Setters?

What are getters and setters in PHP5?
Can someone give me a good example with an explanation?
This is concept for data hiding (or encapsulation) in OOP. For example if you want to have a certain property in your class let's say 'Amount' and give the client of you class the option to change or extract its value You should make your variable 'Amount' private (not visible for those who use your class) and generate two methods a getter and a setter that manipulates your value (that are public).
The reason is to be able to validate data or manipulate it before setting or getting your value. Here is a brief example:
class test {
private $count; //those who use your class are not able to see this property, only the methods above
public function setCount( $value )
{
//make some validation or manipulation on data here, if needed
$this->count = $value;
}
public function getCount()
{
return $this->count;
}
}
Attributes of classes can be private. That means only the object can read and write its own private attributes. Therefore you need methods to do that. The methods that read and return an attribute value are called getters and those that write attributes are called setters. With these methods the classes can control what’s going out and what’s coming in. This concept is called encapsulation.
Getters and Setters are quite new concept in PHP 5 in the form of two magical functions __get() and set(). These two functions set or get property value of an object dramatically as explained in the following example.
class Datatype{
private $thing;
public function _set($k,$v){
$this->$k = $v;
}
public function __get($k){
return $this->$k;
}
}
The PHP manual is really not very verbose on the issue, but there is a very detailed example that should explain a lot. Magic methods: Property overloading

Categories