Ivan Ivković Posted January 18, 2012 Share Posted January 18, 2012 Is there any way to produce a custom magic method? Let's say when I try to get an attribute that doesn't have any value, a method gets called that gives that attribute a value. So I want a method to be triggered when I try to get a value from an attribute that doesn't have any value. Quote Link to comment https://forums.phpfreaks.com/topic/255264-custom-magic-methods/ Share on other sites More sharing options...
scootstah Posted January 18, 2012 Share Posted January 18, 2012 You mean like, __set and __get? Quote Link to comment https://forums.phpfreaks.com/topic/255264-custom-magic-methods/#findComment-1308777 Share on other sites More sharing options...
Ivan Ivković Posted January 19, 2012 Author Share Posted January 19, 2012 Yes, something like that. __set() is called when you try to set a value to a non-existing member. __get() is called when you try to access a non-existing member. I'm trying to find or 'create' a magic method that will respond when I try to access a member that does not have any value. I don't want to overoccupy my constructor... So I want that function to be independent. Quote Link to comment https://forums.phpfreaks.com/topic/255264-custom-magic-methods/#findComment-1309182 Share on other sites More sharing options...
dzelenika Posted January 19, 2012 Share Posted January 19, 2012 Is something like this what you need? <?php ini_set("display_errors", 1); class a { private $p; function __get($name) { return $this->$name ?: "no value"; } function __set($name, $value) { $this->$name = $value; } } $a = new a(); echo $a->p . "<br />"; $a->p = "123"; echo $a->p; ?> dispalys: no value 123 Quote Link to comment https://forums.phpfreaks.com/topic/255264-custom-magic-methods/#findComment-1309192 Share on other sites More sharing options...
ManiacDan Posted January 19, 2012 Share Posted January 19, 2012 Make all of your member variables private, and then __get will always be called when you access a member variable from outside the class. have __get check to see if the value is empty. Quote Link to comment https://forums.phpfreaks.com/topic/255264-custom-magic-methods/#findComment-1309228 Share on other sites More sharing options...
Ivan Ivković Posted January 19, 2012 Author Share Posted January 19, 2012 Dzelenika, this is not what I meant. Thanks. ManiacDan, that's a GREAT IDEA! Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/255264-custom-magic-methods/#findComment-1309424 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.