PHP - Using The __call() Magic Method
Hi there every one, i'm writing a class that create instances of other classes and I want to use the __call() magic method to make it more compact and dynamic. here is a basic example of what I'm trying to achieve.
The code bellow is the working code. Code: [Select] <?php class creator{ private $objects = array(); public function createObj1($param1, $param2, $param3){ $this->objects[]=new Obj1($param1, $param2, $param3); } public function createObj2($param1, $param2){ $this->objects[]=new Obj2($param1, $param2); } } ?> Now I want the same functionality but using just the __call(), something like this Code: [Select] <?php class creator{ private $objects = array(); public function __call($name, $args){ $this->objects[]=new $name($param1, $param2); } } ?> So, the main problem is, in the $args variable i get an array with all the args passed, How can I make the call to create a new object when in the object constructor are individual parameters needed and not an array of parameters. Thank you in advance. Similar Tutorialshey guys i have a __call method in my class...the probelm im having is how to get the arguments into this line Code: [Select] return $this->_db->$method($arguments); if arguments where "test1" and "test2" i want the call to do Code: [Select] return $this->_db->$method("test1", "test2"); the code below will put all arguments into one if anyone can help me on how i can seperate please Code: [Select] public function __call($method, $arguments) { if (method_exists($this->_db, $method)) { $arguments = implode(', ', $arguments); return $this->_db->$method($arguments); } } __call is used when a method has been called, is there anything similar to __call but for properties? I wanted to use __get, but that is only for private properties... In my view file, I instantiate User class and call two methods that have not been declared or initialized in the class: $user = new Models\User(); $user->setFirstName('John'); $user->setLastName('Merlino'); echo $user->getFirstName() . " " . $user->getLastName(); However, I have two private members only available to instances: protected $first_name; protected $last_name; Because I don't want to manually create privileged getters and setters for each of my private members, I use the call method: public function __call($name,$args){ echo $name . "<br />"; echo $args . "<br />"; } Because my methods were not initialized, the interpreter calls the __call method as a last option resort, and passes the name of the method in local variable $name and if exists the arguments passed into the method in local variable $args. Ok so that makes sense. However, when I echo the values of the two variables, I see a blank array created: setFirstName Array setLastName Array getFirstName Array getLastName Array See everytime I call it, there's an array being created. I don't see the purpose of this. Also how often do you use __call() in your php applications, specifically when using MVC? Thanks for response. i have some code which checks to see if a username and an email is in use. from what i can understand, it uses magic quotes to prevent sql injection. i've heard that magic quotes are not going to be in use in php6, so how can i change it so that it uses real escape string instead? if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); if ($check2 != 0) { die('Sorry, the username '.$_POST['username'].' is already in use.'); } if (!get_magic_quotes_gpc()) { $_POST['email'] = addslashes($_POST['email']); } $emailcheck = $_POST['email']; $check = mysql_query("SELECT email FROM users WHERE email = '$emailcheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); if ($check2 != 0) { die('Sorry, the email '.$_POST['email'].' is already registered to another account.'); } Thanks My old server had magic_quotes_gpc turned on. My new one does not. Will mysql_real_escape_string solve all the issues that magic_quotes was used for? My site runs a blogging application and it seems some of the templates which contain a lot of html and css do not insert into the database properly even when using mysql_real_escape_string. Thanks, Brian So, I think you have all heard the news. THEY ARE GONE! Unfortunately, I do have some old code that I do not feel like going line by line and updating. I was wounding if you guys could help me out. I was hoping that there would be a way to set a define of some sort then when I grab something out of an SQL table it will automatically takeout the "\" (Slashes) and when I insert something into the database it will add the slashes... YES I know and have read the statement written by the php group [http://www.php.net/manual/en/securit...uotes.why.php] But i do not particularly want to go through my code and change everything by hand. If you have any idea, or would like me to explain it another way, please post. Any help will be greatly appreciated. --redcrusher hey guys im wdondering if there's a magic method which works like
__GET()but allows you to put a parameter in...thank you <?php class test { public function run() { $this->object->('string'); // __get with parameter? } public function __get($value) { return $this->{$value} } } ?> what are magic methods? when do we need to use magic methods? what are the advantages of using magic methods? thanks in advanced.
My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader.
The error messages I am getting a Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. I have two classes were one extends the other but they both have magic methods __get __call and __set but when trying to call a magic method it conflicts one with the other as you can imagaine...is there a way of getting around this ie. name spaces
or do I simply have to rewrite my classes
thank you
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. I have a class that has the __get and __set magic methods defined. The idea is to use those to communicate with the __get and __set methods in a database table object which is a protected attribute of this class. Then I can quickly build out models without having to bother with method definitions aside from those that need modifications made to the data before saving. The problem is, they don't seem to be doing anything. I get an undefined function error the first time I call getVarx(). I don't actually have any of the attributes I'm trying to get and set defined in the object, but I thought that was the point of these magic methods. Am I missing something here? Thanks, Brandon Hi ! I was seeing the Exception class defined in basic.php and I found that all the methods are final and without body: Code: [Select] final public function getMessage () {}But if I call MyCustomException->getMessage() I get the message. How does it works?? After getting valuable help from DavidAm and wildteen88 I am left with this last piece to the puzzle: I have created a function which identifies the names of multi-value checkbox fields used on a Post page where a form just filled out has been saved in a serialized array which will contain associative arrays wherever the checkboxes have been selected. Now I need for the checkbox associative arrays returned on this Review before-final-saving-page to be detected or identified and then Changed to a comma-delimited array, or maybe it just gets converted to one string with commas separating what were parts of the array--I am not sure about that. At any rate, here are the functions that WORK to do this---but they depend on knowing the specific checkboxes that will show up ahead of time: $postvals['cp_checkbox_amenities']= implode(',', $_POST['cp_checkbox_amenities']); $postvals['cp_checkbox_days']= implode(',', $_POST['cp_checkbox_days']); $postvals['cp_checkbox_3']= implode(',', $_POST['cp_checkbox_3']); So I created a function which polls the form and finds the specific names of the checkboxes used on this page--the function ends like this: $results = $wpdb->get_results($sql); if($results) { foreach ($results as $result): // now grab all ad fields and print out the field label and value echo '<li><span>' . $result->field_name . '</li>'; endforeach; } else { echo __('No checkbox details found.', 'cp'); } } } This returns the following: <li><span>cp_checkbox_help</span></li><li><span>cp_checkbox_charley</span></li><li><span>cp_checkbox_hello</span></li> </li> So, I then tried to REPLACE the hard-code functions I show above that take the checkbox arrays and implode them for saving when this form is updated as comma limited values. I tried various versions of this using the same loop that produced the <li> list with $result->field_name : foreach ($results as $result): // now grab all ad fields and print out the field label and value $postvals['. $result->field_name .']= implode(',', $_POST[ '. $result->field_name .']); endforeach; } else { echo __('No checkbox details found.', 'cp'); } } } Every different way I try to get something either errors out or does not perform the Implode, or notifies me that the Implode is creating problems. SOMEHOW, dynamically for each loop I need for a ' single quote mark to appear on each side of $result->field_name so that I have dynamically written in the php code the equivalent to $postvals['cp_checkbox_amenities']= implode(',', $_POST['cp_checkbox_amenities']); $postvals['cp_checkbox_days']= implode(',', $_POST['cp_checkbox_days']); $postvals['cp_checkbox_3']= implode(',', $_POST['cp_checkbox_3']); the $result->field_name gives me a cp_checkbox_3 or a cp_checkbox_amenities, etc,, but I cannot break it down so that $postvals['$result->field_name']= implode(',', $_POST['$result->field_name']); WORKS and I have tried with [PHP? echo ''' .$result->field_name . ''' ?>] and other ways. Incidentally, ", double quotes don't play nice on this server with PHP 5. And I have tried combinations of " ' double quote then single quote and on the other side ' " inside the associative array brackets.. nothing works--either I get errors, implode warnings, or the arrays of these checkboxes do not get changed to comma delimited arrays if the page loads and saves without errors. I'd appreciate receiving what must be an elegantly simple solution! There's this really old website called http://ipolygraph.com/google/ Basically it mimics the Google homepage (as you can see it's been a while since they've updated) but the idea is really simple but clever. If you go to the search box and type cars (or whatever) and click search, it searches Google for "cars". However if you type something like /php manual/ you'll notice it changes what you're searching to "What is...etc etc". The idea is say you tell your friend you're on Google and you ask them to think of a card, if you type /4c/ is bob thinking of? it'll look as if you're typing "What is Bob thinking of?", when you hit search it'll be the 4 of clubs. Is there any way to make something similar to this? The idea came to me after I learned about the file_get_contents command in PHP. I know that magic __get and __set are invoked automatically when an object is instantiated, but what about stuff like getName() and setName() Code: [Select] class NameClass { private $_name; public function getName() { return $this->_name; } public function setName($value) { $this->_name = $value; } } $someName = new NameClass(); $someName->setName('Bob'); echo $someName->getName(); 1. Could the setName() and getName() just as easily be named something generic like: hotName() coldName() Code: [Select] class NameClass { private $_name; public function hotName() { return $this->_name; } public function coldName($value) { $this->_name = $value; } } $someName = new NameClass(); $someName->coldName('Bob'); echo $someName->hotName(); 2. Also, the setName() and getName() methods must be called manually, right? Unless they are manually called, they just sit there, do nothing, am I correct? Thanks I stumbled upon this book where i first met __set(). When I research it, I met __get(). So there, I don't know who they are. And what they exactly do. If I may ask, is there any tutorial which can give me proper introduction with __set() and __get()? I have read for beginners, but I dont know, maybe I'm too dummy to understand. please bare with me i am just beginner. Thanks in advance. Hi there, I want to allow the ability for DJ's to turn on and off radio requests. Now obviously I've encorporated a check box and submit button within a PHP login. But I was wanting to know if this can be done with PHP or is a database required as the option will need to be remembered for a period of time. I'd probably look to do it by making it display on a page 'requests enabled' if enabled and a blank page if disabled. therefore I could encorporate: <?php if(!empty($requests)) { //requests template } else { //radio requests disabled template } ?> What's the best method for this? Thanks I know I'm posting this inside the PHP coding board but I'm curious on how most handle this situation. I have a page that uses php to retrieve data from my database and I want to have it place a | in between each of the returned data which it does but it still places one after the last returned row. I'm wondering if I should do this with jquery load and then have it place that character in between each of the data or if there's a way to do it with php or what? Any ideas? Code: [Select] <?php require ("../header.php"); ?> <div id="titlehistory" class="content"> <h1 class="pageheading">Title History</h1> <?php $titlesQuery =" SELECT titles.titleName, titles.shortName FROM titles WHERE titles.statusID = 1 ORDER BY titles.ID"; $titlesResult = mysqli_query($dbc,$titlesQuery); ?> <p><span class="minilinks"> <?php while ( $row = mysqli_fetch_array ( $titlesResult, MYSQLI_ASSOC ) ) { $fieldarray=array('titleName','shortName'); foreach ($fieldarray as $fieldlabel) { ${$fieldlabel} = $row[$fieldlabel]; } echo '<a href="/titlehistory/'.$shortName.'">'.$titleName.'</a> |'; } ?> </span></p> <p class="nohistory">Please select a title to view.</p> </div> <?php require ("../footer.php"); ?> I am trying to insert the current Date/Time into mysql database using the following code. I do not understand how $submitDate & $submitTime are to be set. Will this work as coded? Code: [Select] <?php class SubmitDateRecord { const DB_TABLE = 'timesheet'; const DB_FIELD_SUBMIT_TIME = 'submit_time'; private $submitDate; private $submitTime; public function setSubmitDate($submitDate) { $this->submitDate = $submitDate; } public function getSubmitDate() { return $this->submitDate; } public function setSubmitTime($submitTime) { $this->submitTime = $submitTime; } public function getSubmitTime() { return $this->submitTime; } public function addRecord() { $insertTable = "`".self::DB_TABLE."`"; $insertFields[] = "`".self::DB_FIELD_SUBMIT_TIME."`"; $insertValues[] = "'{$this->submitDate} {$this->submitTime}'"; $sqlBuilder = new SQLQBuilder(); $query = $sqlBuilder->simpleInsert($insertTable, $insertValues, $insertFields); $dbConnection = new DMLFunctions(); $result = $dbConnection->executeQuery($query); if ($result) { return true; } else { return false; } } private function _buildRecordObjects($result) { while ($row = mysql_fetch_array($result)) { $submitdateObj = new SubmitDateRecord(); $submitdateObj->setAttendanceId($row['attendance_id']); $submitdateObj->setEmployeeId($row['employee_id']); /* $row['submit_time'] comes in '0000-00-00 00:00:00' format. * We want date in '0000-00-00' format and time in '00:00' format. */ $tmpArr = explode(' ', $row['submit_time']); $submitdateObj->setSubmitDate($tmpArr[0]); $submitdateObj->setSubmitTime(substr($tmpArr[1], 0, 5)); // Omiting 'seconds' part is ok since it is always zero $submitdateObj->setStatus($row['status']); $submitdateArr[] = $submitdateObj; } return $submitdateArr; } } |