PHP - Using $variable = Function() { Return 'hello World'; }
This is object programming right?
Is there a performance issue with this? for example: $notfications = ( blah blah ) ? : ''; then if ($notificatiosn != blabla){ echo 'hey'; }or.... $notifications = function(){ do my stuff here then return 'hey'; }Which way is faster or slower? Reason I Ask this is because I've been doing some object orientated programming in javascript, and didn't know you could do it in php. I'd rather do the objective way so I don't have to use so many freaking variables above the regular way, lol. Edited by Monkuar, 22 January 2015 - 12:22 PM. Similar TutorialsUndefined variable: return line 38 that line is : echo $return; Below is a look at my full code. Code: [Select] <?php class cms { var $host; var $username; var $password; var $db; function connect() { $con = mysql_connect($this->host, $this->username, $this->password) or die(mysql_error()); mysql_select_db($this->db, $con) or die(mysql_error()); } function get_content($id = ''){ if($id !=""): $id = mysql_real_escape_string($id); $sql = "SELECT * FROM cms_content WHERE id = '$id'"; $return = '<a href="index.php">Go Back?</a>'; else: $sql = "SELECT * FROM cms_content ORDER BY id DESC"; endif; $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) != 0): while($row = mysql_fetch_assoc($res)) { echo '<h1><a href="index.php?id=' . $row['id'] .'">' . $row['title'] .'</a></h1>'; echo '<p>' . $row['body'] . '</p>'; } else: echo '<p> Sorry! This Page doesn\'t exist!</p>'; endif; echo $return; } }//Ends our class ?> Hey, In my script I am currenlty working on I have 2 classes one which calls the second in the hope it will return a value to it but doesnt send the variable back. The example code below give you and idea of what I am looking for as my script it too long to add. Code: [Select] class oneClass{ function bar(){ $var1 = "test" $two = twoClass(); $result = $two->foo($var1); echo $result; } } class twoClass{ function foo($var1){ $result = $var1 . ' is successful!'; $this->fooTwo($result); } function fooTwo($result){ $result = $result . ' Pass me back now?'; return($result); //Want to pass the variable back to "oneClass->bar();" } } // Starts script $testme = new oneClass(); $testme->bar(); This is a very simple example but states what i am wanting to. Any ideas would be much appreciated! Thanks I'm not versed in PHP OOP and I have some code that I need to echo out onto a page. I don't know what the meaning of $ct->something is in this code. Is this an array of some type? How do I echo out the $ct->title onto another page? Use a function call? I just don't know what all of the $ct variables are and how to get to them. Any help is appreciated. Code: [Select] function current_theme_info() { $themes = get_themes(); $current_theme = get_current_theme(); if ( ! isset( $themes[$current_theme] ) ) { delete_option( 'current_theme' ); $current_theme = get_current_theme(); } $ct->name = $current_theme; $ct->title = $themes[$current_theme]['Title']; $ct->version = $themes[$current_theme]['Version']; $ct->parent_theme = $themes[$current_theme]['Parent Theme']; $ct->template_dir = $themes[$current_theme]['Template Dir']; $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir']; $ct->template = $themes[$current_theme]['Template']; $ct->stylesheet = $themes[$current_theme]['Stylesheet']; $ct->screenshot = $themes[$current_theme]['Screenshot']; $ct->description = $themes[$current_theme]['Description']; $ct->author = $themes[$current_theme]['Author']; $ct->tags = $themes[$current_theme]['Tags']; $ct->theme_root = $themes[$current_theme]['Theme Root']; $ct->theme_root_uri = $themes[$current_theme]['Theme Root URI']; return $ct; } Hello All, I have two php files original.php and return.php retrun.php file returns a variable after I pass $channel_name to it Code: [Select] return $return_variable; I want to assign this return variable to a variable in original.php Something like this Code: [Select] $results = include ('return.php?channel='.$channel_name.'');I am not sure how to do the above code. When I call the return.php from a browser it works properly. Thanks for any help I think I might have already asked something similar, but... my code has: $ip = gethostbyaddr($_SERVER['REMOTE_ADDR']); $host = $_SERVER['HTTP_HOST']; my field header for "$host" is "VISITOR DOMAIN ADDRESS". I'm not sure what I was thinking. That's not possible to capture is it? Last I read, and I think someone here told me, it is only possible to capture the IP and server name of the requesting computer? the var $ip in my report, for instance, returns: 173-28-199-198.client.mchsi.com if I visit the page, and that is the name of the server assigned to my ISP. on PHP's doc page, there are the vars REMOTE_HOST and REMOTE_USER and I haven't tried those. Their example does not list any return value for those vars. what do they return? Edited November 23, 2019 by ajetrumpetHi, i got this function to get the wordCount that i store in a tabel: Code: [Select] function getWordCount($word) { $query = "SELECT count FROM uniqueWords WHERE word='$word'"; $data = execQuery($query); return $data; } Only it returns an array, what i want is to have it return a integer, how can i do that? let say i have a function function checkme($x) { if(strlen($x)>10) { return $x; } else { return false; } } $variable=checkme("5"); so two questions i wish to ask... 1. If i wish to get the empty string for the $variable, then is it correct to have return false there? 2. If it is true that return shall not be used twice in a function as it will somehow reduce bytes space or something like that?? thanks in advance Hi all, can you give me suggestion how to return value from function like this Code: [Select] function returnArray(){ for($i=1; $i<=3; $i++){ return $i; //how to return this as array?? } } when I code "echo" inside the function then call the function it give me output => 123 but when I code "return" inside the function, it will give output => 1 Can you suggest me how to output it as array? I have found postings close, but not close enough to find my error. I am looking up data from a MySql table and putting it in a dropdown box on a form. I can select the item, but apparently not really. I am not able to echo it, or post it to a record. I'm sure I am missing something simple, but... Code attached if anyone can show me the errors of my ways. Thank you. Hi,Dear Frnds...........................I Hope U r all fine. I am using php.Here is the problem in the Return array from function. This is the code. Code: [Select] <?php $store = array(); $test = get_my_links(); print_r($store); function get_my_links() { $my_array = array('e','f','g'); foreach($my_array as $key=> $list) { $store[] = $list; } return $store; } ?> Suppose the array is maked dynamically. please help me..THANKS... I hate array... 😞 So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array. Then in my HTML, I iterate through this array to display all of the photos for my gallery. Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array. It seems to me that I need to encapsulate my code inside a function? Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever. I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script. This is what I have so far... function getPhotoFilesArray($photoPath){ $photoFiles = array(); <code to find corresponding files> $photoFiles gets populated in a loop return $photoFiles; }
Then in my calling script, I have... <?php require_once('../../../secure_outside_webroot/config.php'); require_once(WEB_ROOT . 'utilities/functions.php'); getPhotoFilesArray($photoPath); var_dump($photoFiles);
I get some error...
Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
<br> Would appreciate help getting this to work!
Edited December 6, 2019 by SaranacLake My tree gather function gives me multidimensional array. However i want it to be one dimensional . I was getting one dimensional earlier however i forgot how i got it. Can someone please tell me my mistake Code Code: [Select] <?php include'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $eh[] = tree_gather($array['lchild']); $child = array_merge($child, $eh); $eh1[] = tree_gather($array['rchild']); $child = array_merge($child, $eh1); } return $child; } $pair = tree_gather(1000000); echo "<pre>"; print_r($pair); echo "</pre>"; ?> Output Code: [Select] Array ( [0] => 3632873 [1] => 5951538 [2] => Array ( [0] => 8930480 [1] => 7563232 [2] => Array ( [0] => 1144744 [1] => 4386810 [2] => [3] => ) [3] => ) [3] => ) not sure if this is possible but i do not know how to return multiple values and read them where the call was made. Code: [Select] $string = "clause1"; func1($string); // somehow read the response and use the return values seperately. // both $string2 and $string3 Code: [Select] function func1($input) { if ($input == "clause1") { $string2= "value2"; $string3= "value6"; } if ($input == "clause2") { $string2= "value3"; $string3= "value7"; } if ($input == "clause3") { $string2= "value4"; $string3= "value8"; } if ($input == "clause4") { $string2= "value5"; $string3= "value9"; } return ($requesttype, $messagetitle); } Hello everyone, Pretty much what I am trying to do is run a query and based of the queries result, return a string - as of now it is turning up blank and cant seem to pass any strings through the function. Current function: function addNewBookmark($hash,$url,$title,$username){ Code: [Select] $query = "INSERT INTO bookmarks (hash,url,title,username) VALUES '".md5($hash)."', '".$url."', '".$title."', '".$username."')"; $result = mysql_query(query, $this->connection); $message = ''; if(mysql_affected_rows($this->connection)!=1) { $message = 'This URL already exists in the database!'; return $message; } else $message = 'The URL was shared!'; return $message; } The above code seems to run fine, just cant seem to pass a string...read that you can possibly use a __toString function? but that keeps throwing errors when I try to work with it. Thanks all! This is my error: Code: [Select] Fatal error: Can't use function return value in write context in /home/a8152576/public_html/SecretSanta.html on line 41 confused about why. This is the line 41: if(isset($_POST('submit')){ this is the php of my page (without the mysql data): <?php class functions{ public static function chooseGiftee($SS){ $done = false; while($done=false){ $sqllink= mysql_connect($mysql_host,$mysql_user,$mysql_password); if(!$sqllink){ echo "Could not connect! Please Try Again"; mysql_close($sqllink); } else { $selectGiftee = "SELECT * FROM SecretSantas ORDER BY RAND() LIMIT 0,10;"; while($row=mysql_fetch_array($result)){ $results = mysql_query($selectGiftee); if(!$row['Gifter']=''){ $done=false; } else { $gifteeResults = $row['Name']; $addSS = "INSERT INTO SecretSantas (Gifter) VALUES ('" .$SS. "')"; $done=true; return $gifteeResults; } } } mysql_close($sqllink); } } } if(isset($_POST('submit')){ $echoName = functions::chooseGiftee($_POST['gifterName']); echo $echoName; } ?> This is html: <form id="form1" name="form1" method="post" action=""> <p> <label>Your Name: <input type="text" name="gifterName" id="gifterName" /> </label> <input type="submit" name="submit" id="submit" value="Submit" /> </p> <p> </p> </form> Confused about the issue, first time using functions. Thanks in advance, Brandon Hi, I have some strange issues with my code: Code: [Select] <?PHP session_start(); $loginid = $_SESSION["valid_id"]; // First check if we are guest or user. if (!$_SESSION["valid_email"]) { $visitor = "yes"; } else { $visitor = "no"; $email = $_SESSION['valid_email']; $userid = $_SESSION['valid_id']; } //Load Header (blue menu) require("./inc/header.php"); //Load Sub-acc (silver account menu) require("./inc/sub-group.php"); //Load nav-group (Tabs) require("./inc/nav-group.php"); //Load Config file require("./inc/config.php"); //Set & get profile ID $getid = $_GET["id"]; //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); } //If we are guest, do we allow anon access to the profile IF ($row["privacy"] <= 10 && $visitor = "yes") { exit("You may not view this profile as a visitor, due to the users privacy settings"); } //Let's check if we are friends ELSEIF ($visitor = "no") { $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); $row2 = mysql_fetch_array($result2); $friends = $row2["status"]; if (mysql_num_rows($result2) = 0) { $friends = "no"; } } //If we are friend, do we allow access to the profile IF ($row["privacy"] >= 9 && $friends != 1) { exit("You may not view this profile because of the privacy settings."); } $row = mysql_fetch_array($result); $memgroup = $row["group"]; IF ($row["activated"] != 1) { exit("This account is suspended and cannot be viewed."); } //Check what group member is in. $result2 = mysql_query("SELECT * FROM profiles_groups WHERE id=('$memgroup') LIMIT 1"); $row2 = mysql_fetch_array($result); ?> Alright, so the error: Fatal error: Can't use function return value in write context in C:\xampp\htdocs\prog\profile.php on line 45 Code: [Select] 42. $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); 43. $row2 = mysql_fetch_array($result2); 44. $friends = $row2["status"]; 45. if (mysql_num_rows($result2) = 0) Alright, this is one thing that bothers me, the other is: Code: [Select] //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); I tried to put an invalid ID, and already here the script should have died/exited before executing the parts of the code that doesn't work. I tested my code on another page and it works flawlessly, perhaps this error is just generated before it actually exists i dunno.. Any way, any help is much appreciated } HI guys I have vreated a site and am now trying to validate the ip address i have created a function but am failing to get it to work i need to add the errors to add to the errors array but instead it keeps resetting and leaving me with the last error that is returned any help would be greatly appreciated im a newbie so if i can understand the concept behind whats happening it will be of great benefit Thanks Sean heres the code // Function validateIpaddress($address,$record,$errors) // { // if ($address !=="" or $address !=="ip_address") // { // Print_r($address); // echo "<br><br>"; // $fullstoppos = strpos(($address), "."); // echo "strpos = $fullstoppos"; // $fullstoppos2 = strpos(($address), ".", $fullstoppos+1); // echo "strpos2 = $fullstoppos2"; // $fullstoppos3 = strpos(($address), ".", $fullstoppos2+1); // echo "strpos3 = $fullstoppos3"; // } // if ($fullstoppos !==4 && $fullstoppos2 !==9 && $fullstoppos3 !==14) // { // $errors[] = "<br><font color='red'>Please correct the following.Or contact your client manager for assitance.<br>* $record is a required field.An ip address is a 16 digit numerical value. </font>"; // } // } $errors = validateIpaddres($_POST['destinationPoint'],A/AAAA record, $errors) hi guys i am including a function in my main script, and i'm calling it aftwerwards. except i cannot echo successfully the data in the $result variable, why? function echoResult(){ $result = 'dan'; return $result; } // 1 echo echoResult(); // don't work. i get empty data. // 2 $fnResult = echoResult(); echo $fnResult; // don't work. get empty data. i have ran get_included_files and the include is being made successfully. i read on php.net and these are the examples they use (user comments!) how do i get the data out of the function and echo it, using this way? I'm trying to return to array of letters that bruteForce finally decides upon. However, I can't seem to pass the array to librarySolve. I'm feeling dumb, any help? Code: [Select] function librarySolve($string){ $temp = $this->bruteForce($string, FALSE, 0); return $temp; } function bruteForce($string, $state, $trys){ $base = $string; $state = $state; $new_letters = array(); if($trys <= 6000){ $this->new_letters = $this->generateRandomCipher(); $string = preg_replace('/[^a-zA-Z0-9-\s]/', '', $string); for($a=0;$a<=strlen($string);$a++){ $letter = substr($string, $a, 1); $pattern = "/[A-Z]/"; if(preg_match($pattern, $letter)!=0){ $new_letter = $this->new_letters[$letter]; } else if(preg_match($pattern, $letter)==0) { $new_letter = $letter; } $decipher .= $new_letter; } $word_array = explode(" ", $decipher); $count = 0; for($a=0;$a<count($word_array);$a++){ $do = $this->checkWord($word_array[$a]); if(!empty($do)){ $count++; } } if($count>=2){ $state = TRUE; } else { $state = FALSE; } if($state==TRUE){ return $this->new_letters; } else { $trys++; $this->bruteForce($base, $state, $trys); } } } |