PHP - Custom Magic Methods?
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. Similar Tutorialshey 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. 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
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 Well the title may seem a bit confusing, but heres an example: Code: [Select] <?php class User{ public $uid; public $username; protected $password; protected $email; public $usergroup; public $profile; public function __construct($id){ // constructor code inside } public function getemail(){ return $this->email; } public function getusergroup(){ return $this->usergroup; } public function getprofile(){ $this->profile = new UserProfile($this->uid); } } class UserProfile(){ protected $avatar; protected $bio; protected $gender; protected $favcolor; public function __construct($id){ // constructor code inside } public function formatavatar(){ // avatar formatting code inside } public function formatusername(){ // format username? } } ?> As you can see, the User class(an outer class) has a property called Profile, which can be instantiated as a UserProfile object(an inner class). The two objects have distinct functionalities, but there are times when the UserProfile object needs to access property and methods from the user object. I know its easy for outer class to access methods from inner class by using the single arrow access operator twice, but how about the other way around? Lets say from the above example the userprofile can format the username displayed to the screen by adding a sun to the left of the username if the usergroup is admin, a moon if the usergroup is mod, and nothing if its just a member. The usergroup property is stored in the outer class, and can be accessed with this $user->getusergroup() method only. I know I can always do the hard way by passing a user object to the method's argument, but is there an easier way for the inner class UserProfile to access properties/methods for outerclass User? If so, how can I achieve that? I'm sure it's not much, but I'm not understanding something with custom error handlers: I've created a custom error handler, which I initially set when my page loads : set_error_handler(array ( new ErrorHandler(), 'handleError' ));
It seems to catch all internal PHP errors, such as if I: var_dump($non_existing_var); right after the set_error_handler.... Now, I have an object that throws an exception after: set_error_handler(array ( new ErrorHandler(), 'handleError' )); $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception ... I thought that with an error handler set, I could 'skip' the try/catch for it, but doing so, PHP spits out in its internal log: PHP Fatal error: Uncaught CorbeauPerdu\i18n\LocaleException: ....
My error handler doesn't catch it at all before, thus my page breaks!! If I want it to go through the error handler, I have to init my Locale with a try/catch and use trigger_error() like so: set_error_handler(array ( new ErrorHandler(), 'handleError' )); try { $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception } catch(Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } ... Is this normal ? I thought one of the goals of the error_handler was to catch anything that wasn't dealt with? Thanks for your answers! 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 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?? 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. hey 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); } } 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. I don't know if this belongs here; sorry if it doesn't. I'm using a method=get on a form as I need to pass information through a URL once the form has been submitted. But I also need to INSERT some data from that form to multiple tables. - How can I stop the GET from passing my other variables into the URL? - How do I make the form submit to itself? I need to use the 'index.php?p=checkout' as this matches with a switch statement, which matches to the checkout page. The function PHP_SELF will just refresh to the index.php page, which will not have any of this checkout's page validation. Here's my code: Code: [Select] <h2>Please enter your details</h2> <h3>All fields required</h3> <div id="checkout"> <?php if (isset($_GET['checkout'])){ require_once ('./includes/connectvars.php'); $title = $_GET['title']; $fname = $_GET['fname']; $sname = $_GET['sname']; $ctype = $_GET['ctype']; $cnumber = md5($_GET['cnumber']); $syear = $_GET['smonth'] . $_GET['syear']; $fyear = $_GET['fmonth'] . $_GET['fyear']; $service = $_GET['cardAuth']; $amount = $_REQUEST[$total]; $msg = rand(1000,9999); $api = 'd41d8cd98f00b204e9800998ecf8427e'; $b_house = $_GET['b_house']; $b_postcode = $_GET['b_postcode']; $b_city = $_GET['b_city']; $b_country = $_GET['b_country']; $d_house = $_GET['d_house']; $d_postcode = $_GET['d_postcode']; $d_city = $_GET['d_city']; $d_country = $_GET['d_country']; $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query = "INSERT INTO customer (cust_id, first_name, last_name) VALUES ('', '$fname', '$sname') "; $query = "INSERT INTO bill (cust_id) VALUES ('') "; $query = "INSERT INTO deliver (cust_id) VALUES ('') "; mysqli_query($dbc, $query); } //.'service='.$service.'msg_id='.$msg.'num_md5='.$cnumber.'amount='.$amount.'currency=GBP'.'api_key='.$api. ?> <form method="get" action="index.php?p=checkout"> <table> <tr> <td><input type="hidden" name="cardAuth" /></td> </tr> <tr> <td> Title: </td> <td> <select name="title" value="<?php if (!empty($title)) echo $title; ?>" > <option></option> <option>Mr</option> <option>Sir</option> <option>Ms</option> <option>Miss</option> <option>Mrs</option> </select> </td> </tr> <tr> <td> First Name: </td> <td> <input type="text" name="fname" value="<?php if (!empty($fname)) echo $fname; ?>"/> </td> </tr> <tr> <td> Surname: </td> <td> <input type="text" name="sname" value="<?php if (!empty($sname)) echo $sname; ?>"/> </td> </tr> <tr> <td> </td> </tr> <tr> <td> Card Type: </td> <td> <select name="ctype" value="<?php if (!empty($ctype)) echo $ctype; ?>"> <option>mastercard</option> <option>visa</option> <option>amex</option> <option>solo</option> <option>maestro</option> <option>jcb</option> <option>diners</option> </select> </td> </tr> <tr> <td> Card Number: </td> <td> <input type="text" name="cnumber" value="<?php if (!empty($cnumber)) echo $cnumber; ?>"/> </td> </tr> <tr> <td> Valid From: </td> <td> <select name="smonth" value="<?php if (!empty($smonth)) echo $smonth; ?>"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> <select name="syear" value="<?php if (!empty($syear)) echo $syear; ?>"> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> </select> </td> </tr> <tr> <td> Expires End: </td> <td> <select name="fmonth" value="<?php if (!empty($fmonth)) echo $fmonth; ?>"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> <select name="fyear" value="<?php if (!empty($fyear)) echo $fyear; ?>"> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> </select> </td> </tr> <tr> <td><h4>Billing Address</h4></td> </tr> <tr> <td> House Name/ Number: </td> <td> <input type="text" name="b_house" /> </td> </tr> <tr> <td> Postcode </td> <td> <input type="text" name="b_postcode" /> </td> </tr> <tr> <td> City: </td> <td> <input type="text" name="b_city" /> </td> </tr> <tr> <td> Country: </td> <td> <input type="text" name="b_country" /> </td> </tr> <tr> <td><h4>Delivery Address</h4></td> </tr> <tr> <td> House Name/ Number: </td> <td> <input type="text" name="d_house" /> </td> </tr> <tr> <td> Postcode </td> <td> <input type="text" name="d_postcode" /> </td> </tr> <tr> <td> City: </td> <td> <input type="text" name="d_city" /> </td> </tr> <tr> <td> Country: </td> <td> <input type="text" name="d_country" /> </td> </tr> <tr> <td> </td> </tr> <tr> <td> </td> <td> <input type="submit" name="checkout" value="Checkout"/> </td> </tr> </table> </form> </div> Hi, I am trying to get my head around classes, interfaces and methods for different animals
this is what I have so far: <?php interface animal { function walk(); function fly(); function swim(); } class monkey implements animal{ const interface1 = "I am from test class"; function noise() { echo "ooh ooh ah ah!"; } function walk() { echo "monkey is walking"; } function fly() { echo "monkey is Flying"; } function swim() { echo "monkey is Swimming"; } public function display() { echo monkey::interface1; echo PHP_EOL; } } class bear implements animal{ const interface1 = "I am from test class"; function noise() { echo "Grrr!"; } function walk() { echo "Bear is walking"; } function fly() { echo "Bear is Flying"; } function swim() { echo "Bear is Swimming"; } public function display() { echo bear::interface1; echo PHP_EOL; } } $Obj = new monkey(); $Obj->display(); $Obj1 = new bear(); $Obj1->display(); ?> I'm a bit stumped as animal interface not calling all functions?! please help I am trying to run the function "age", using the last line, I thought that is how I could to access that method, but that doesn't work. Code: [Select] <?php require_once '../phpLive/phpLive.php'; $live->myClass = (object)array( "name" => "Billy Bob Joe", "age" => function($dob){ // Run some code } ); echo $live->myClass->age("1986-07-22"); ?> I get the following error when trying to do that. Quote Fatal error: Call to undefined method stdClass::age() in /xxx/new.plugin.php on line 9 Any Ideas how I can access that method? Thanks! |