On Zend Quick Start Guide here http://framework.zend.com/manual/en/learning.quickstart.create-model.html we can see:
class Application_Model_Guestbook
{
protected $_comment;
protected $_created;
protected $_email;
protected $_id;
public function __set($name, $value);
public function __get($name);
public function setComment($text);
public function getComment();
...
I normally create my getters and setters without any magic method. I've seen this on the quick guide, and I don't understand why may we need this.
Can anyone help me out?
Thanks a lot
You (usually) never call __set or __get directly. $foo->bar will call $foo->__get('bar') automatically if bar is not visible and __get exists.
In the tutorial you've linked to, the getter and setter get set up to automatically call the appropriate individual get/set functions. So $foo->comment = 'bar' will indirectly call $foo->setComment('bar'). This isn't necessary... it's only a convenience.
In other cases, __get can be useful to create what looks like a read-only variable.
If you "make your own" getters and setters, you'll be making two functions for each property: getPropname() and setPropname. By using PHP's "magic method" setter/getter, you don't write individual methods for each property. You can set/get properties as if they were public. Within the overload functions, you add the logic specific to each property. Example:
public function __set($name, $value) {
switch ($name) {
case 'comments':
// do stuff to set comments
break;
case 'parent_user':
// do stuff to set parent user
break;
}
}
public function __get($name) {
switch ($name) {
case 'comments':
// do stuff to get comments
break;
case 'parent_user':
// do stuff to get parent user
break;
}
}
Now I can access comments by using $obj->comments to either set or get.
To achieve the above functionality without using the overloads, I would have had to write 4 different methods instead. This is really more about code organization, both in terms of the actual file and in terms of creating a standardized interface for objects within a project.
I personally prefer to do as you do and write separate methods for each property that I need a complex getter/setter. To me, it is more clearly organized, and there is a clear separation between "simple" properties of an object and those properties which have greater complexity or one-to-many relationships.
The __get and __set magic methods exist for TWO reasons:
So that you don't have to spend time creating vanilla accessor methods for all of your properties.
To allow you to implement property overloading.
If you have properties that need special treatment, then the magic methods are not for you. However, if your properties simply contain data and there are no dependencies then there's no reason NOT to use the magic methods.
Further on the tutorial it gets you to modify the __get() and __set() methods so you'll see why they're there.
Having magic handling like that can allow you to do some neat stuff like even making "read only" properties and can prevent you from bloating your class with a messy load of getter/setters.
You'll run into problems when you've used __set and want to override the setter functionality in a child class. You'll have to copy the entire code in __set and change only the specific part instead of just simply overwrite one specific setter function -> redundant code
This problem can be avoided by calling the specific setter in __set (thanks to cHao for the tip).
Example:
class Foo1 {
protected $normal;
protected $special;
public function setSpecial($special) {
if ($special == isReallySpecial()) {
$this->special = $special;
}
}
public function __set($key, $value) {
switch ($key) {
case 'normal':
$this->normal = $value;
break;
case 'special':
$this->setSpecial($value);
}
}
}
class Foo2 extends Foo1 {
public function setSpecial($special) {
if ($special == isNotReallySpecial()) {
$this->special = $special;
}
}
}
Related
How can I store a model that was returned from $bean->box() in RedBean?
For example, the following code doesn't work (it just inserts an empty row):
class Model_Comment extends RedBean_SimpleModel {
public $message;
}
$bean = R::dispense('comment');
$model = $bean->box();
$model->message = "Testing";
R::store($model);
It works if I use $model->unbox()->message = "Testing", but that's probably gonna get annoying real quick...
Obviously the code above is just an example, I could just set the property message on $bean here, but I want to be able to box a bean and pass it to other methods.
Is this how it's supposed to work, or am I missing something here?
This turned out to be caused by a "gotcha" when dealing with PHP's "magic" getter- and setter methods __get() and __set().
Looking at the source code for RedBean_SimpleModel, it actually uses the magic __set() method to update its bean when setting a property.
Here's comes the gotcha, straight from the PHP documentation:
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
__isset() is triggered by calling isset() or empty() on inaccessible properties.
__unset() is invoked when unset() is used on inaccessible properties.
So it turns out that __set() is never called for an existing (accessible) class member, i.e. public $message. So I could just remove all the public fields from the class and that would solve the problem, but then I'd lose all the autocomplete functionality and lint checking in my IDE.
So I came up with this solution instead:
class MyBaseModel extends RedBeanPHP\SimpleModel {
public function __construct(){
foreach( get_object_vars($this) as $property => $value ){
if( $property != 'bean' )
unset($this->$property);
}
}
}
class Model_Comment extends MyBaseModel {
public $message;
}
This effectively removes all member variables from the class MyBaseModel when it's instantiated, except $bean, which of course is a vital part of RedBeanPHP_SimpleModel.
Now I can easily subclass MyBaseModel and have all the public fields I need in my subclass models, and the code in the original question will work.
Assuming that I have to create a class that takes some text do some processing and return it ... with no dependency and it's a stateless class..
I'd like to know would be better to create a stateless class without constructor or just create a static class (in php it's just Static methods)
class like this:
class ClassName
{
public function processText($text)
{
// Some code
$text = $this->moreProcessing($text);
return $text;
}
protected function moreProcessing($text)
{
return $text;
}
}
and this:
class ClassName
{
public static function processText($text)
{
// Some code
$text = static::moreProcessing($text);
return $text;
}
protected static function moreProcessing($text)
{
return $text;
}
}
I Know that dependency injection into the class where these classes are used would be better but assume that I just won't have dependency injection..
My question is mainly would it be better to create static class for the simple example above?
Practically you will see no difference whatsoever.
It's only in the syntax, and the ability of a constructor to perform stuff automatically, though you still have to create instances to invoke the constructor, which in this case is not far off calling some equivalent static member function.
However, non-static member functions are supposed to affect internal state so, if you have no state, static member functions seem more conventional, and will be slightly less surprising to users of the class.
The best approach, though, is to stick your functions in a namespace. Classes are for data and functions operating on that data... even static ones.
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.
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;
}
}
I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it.
I didn't want to just dump a bunch of code in the question so I've posted the code for the class on refactormycode.
base class for easy class property handling
My thought was that people can either post code snippets here or make changes on refactormycode and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that.
At any rate, on to the class itself:
I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this:
public function getFirstName()
{
return $this->firstName;
}
public function setFirstName($firstName)
{
return $this->firstName;
}
Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me).
Basically, the PropertyHandler class has a __call magic method. Any methods that come through __call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into __call is "getFirstName", the array key is "FirstName".
I liked using __call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the __get & __set magic methods don't do that.
So here's an example of how it would work:
class PropTest extends PropertyHandler
{
public function __construct()
{
parent::__construct();
}
}
$props = new PropTest();
$props->setFirstName("Mark");
echo $props->getFirstName();
Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values.
The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way.
class PropTest2
{
private $props;
public function __construct()
{
$this->props = new PropertyHandler();
}
public function __call($method, $arguments)
{
return $this->props->__call($method, $arguments);
}
}
$props2 = new PropTest2();
$props2->setFirstName('Mark');
echo $props2->getFirstName();
Notice how the subclass has a __call method that just passes everything along to the PropertyHandler __call method.
Another good argument against handling getters and setters this way is that it makes it really hard to document.
In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist.
I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity.
The way I do it is the following:
class test {
protected $x='';
protected $y='';
function set_y ($y) {
print "specific function set_y\n";
$this->y = $y;
}
function __call($function , $args) {
print "generic function $function\n";
list ($name , $var ) = split ('_' , $function );
if ($name == 'get' && isset($this->$var)) {
return $this->$var;
}
if ($name == 'set' && isset($this->$var)) {
$this->$var= $args[0];
return;
}
trigger_error ("Fatal error: Call to undefined method test::$function()");
}
}
$p = new test();
$p->set_x(20);
$p->set_y(30);
print $p->get_x();
print $p->get_y();
$p->set_z(40);
Which will output (line breaks added for clarity)
generic function set_x
specific function set_y
generic function get_x
20
generic function get_y
30
generic function set_z
Notice: Fatal error: Call to undefined method set_z() in [...] on line 16
#Brian
My problem with this is that adding "more logic later" requires that you add blanket logic that applies to all properties accessed with the getter/setter or that you use if or switch statements to evaluate which property you're accessing so that you can apply specific logic.
That's not quite true. Take my first example:
class PropTest extends PropertyHandler
{
public function __construct()
{
parent::__construct();
}
}
$props = new PropTest();
$props->setFirstName("Mark");
echo $props->getFirstName();
Let's say that I need to add some logic for validating FirstNames. All I have to do is add a setFirstName method to my subclass and that method is automatically used instead.
class PropTest extends PropertyHandler
{
public function __construct()
{
parent::__construct();
}
public function setFirstName($name)
{
if($name == 'Mark')
{
echo "I love you, Mark!";
}
}
}
I'm just not satisfied with the limitations that PHP has when it comes to implicit accessor methods.
I agree completely. I like the Python way of handling this (my implementation is just a clumsy rip-off of it).
Yes that's right the variables have to be manually declared but i find that better since I fear a typo in the setter
$props2->setFristName('Mark');
will auto-generate a new property (FristName instead of FirstName) which will make debugging harder.
I like having methods instead of just using public fields, as well, but my problem with PHP's default implementation (using __get() and __set()) or your custom implementation is that you aren't establishing getters and setters on a per-property basis. My problem with this is that adding "more logic later" requires that you add blanket logic that applies to all properties accessed with the getter/setter or that you use if or switch statements to evaluate which property you're accessing so that you can apply specific logic.
I like your solution, and I applaud you for it--I'm just not satisfied with the limitations that PHP has when it comes to implicit accessor methods.
#Mark
But even your method requires a fresh declaration of the method, and it somewhat takes away the advantage of putting it in a method so that you can add more logic, because to add more logic requires the old-fashioned declaration of the method, anyway. In its default state (which is where it is impressive in what it detects/does), your technique is offering no advantage (in PHP) over public fields. You're restricting access to the field but giving carte blanche through accessor methods that don't have any restrictions of their own. I'm not aware that unchecked explicit accessors offer any advantage over public fields in any language, but people can and should feel free to correct me if I'm wrong.
I've always handled this issue in a similar with a __call which ends up pretty much as boiler plate code in many of my classes. However, it's compact, and uses the reflection classes to only add getters / setters for properties you have already set (won't add new ones). Simply adding the getter / setter explicitly will add more complex functionality. It expects to be
Code looks like this:
/**
* Handles default set and get calls
*/
public function __call($method, $params) {
//did you call get or set
if ( preg_match( "|^[gs]et([A-Z][\w]+)|", $method, $matches ) ) {
//which var?
$var = strtolower($matches[1]);
$r = new ReflectionClass($this);
$properties = $r->getdefaultProperties();
//if it exists
if ( array_key_exists($var,$properties) ) {
//set
if ( 's' == $method[0] ) {
$this->$var = $params[0];
}
//get
elseif ( 'g' == $method[0] ) {
return $this->$var;
}
}
}
}
Adding this to a class where you have declared default properties like:
class MyClass {
public $myvar = null;
}
$test = new MyClass;
$test->setMyvar = "arapaho";
echo $test->getMyvar; //echos arapaho
The reflection class may add something of use to what you were proposing. Neat solution #Mark.
Just recently, I also thought about handling getters and setters the way you suggested (the second approach was my favorite, i.e. the private $props array), but I discarded it for it wouldn't have worked out in my app.
I am working on a rather large SoapServer-based application and the soap interface of PHP 5 injects the values that are transmitted via soap directly into the associated class, without bothering about existing or non-existing properties in the class.
I can't help putting in my 2 cents...
I have taken to using __get and __set in this manor http://gist.github.com/351387 (similar to the way that doctrine does it), then only ever accessing the properties via the $obj->var in an outside of the class. That way you can override functionality as needed instead of making a huge __get or __set function, or overriding __get and __set in the child classes.