PHP - Accessing A Variable Inside The Parent Function From A Child Function
Hello all, I have some piece of code that is nested like this
$variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance Similar TutorialsCode: [Select] Main Object ( [Visitor] = Visitor Object ( [user_info] => Array ( [username] = user [user_id] = 1 ) ) [Room] = Room Object ( [info] = Array( [id] = 1 [name] = Lobby ) [messages] = Messages Object ( [messages] = Array ( [0] = Array() ) ) ) ) Is there a way to get the visitor info within the Messages Object? I'm building it such as $Main = new Main; $Main->Visitor = new Visitor; $Main->Room = new Room; $Main->Room->Messages = new Messages; so they're not static I know that I can pass the $this var through each but that duplicates the class each time and I'm 99% sure that's bad. I dont know why I'm having so many problems with this. I need to get a variable that defined in an included file inside of a function I've got this Inside file.php I've got the $variable1 and $variable2 defined (they're dynamic/different to each user) include('file.php'); function foo() { GLOBAL $variable1, $variable2; echo $variable1; echo $variable2; } foo(); Yet it outputs nothing? If I Include file.php right inside of the function it works however. Any idea? Question 1) Is the only and proper way to call a parent function "parent::function()"? Are there other/better ways from within a child function? Question 2) What are the deciding factors for when to make a function or attribute static? How do you make that decision? Assuming 5.3... Thanks. I thought I was a beginner PHPer but now I'm not even sure I'm that. I have this class here which starts with: Code: [Select] private static $FormatType = ""; but then further down: Code: [Select] public function SetFormatType($NewFormatTypeId) { $this->FormatType = $NewFormatTypeId; } public function GetFormatType() { return $this->FormatType; } Do you suppose that the original developer just had a singleton or something, then latter on he found that he was making more instances and PHP tolerates this behavior? Or am I missing something? When I put this chunk of code into it's own function: function fetch_all ($dbc, $query) { include ('knuffix_list_func.php'); pagination_start ($dbc, $query); $offset = $pag_array[0]; $rows_per_page = $pag_array[1]; $query = $query . " LIMIT $offset, $rows_per_page"; echo "test query: " . $query; knuffix_list ($query, $dbc); pagination_end ($pag_array); } And when I echo out the query as you can see in the example, then I notice that the variables $offset and $rows_per_page never get appended. I set the variable $pag_array to a global inside the function pagination_start(). It usually works when I DON'T wrap a function around this chunk of code, but if I do wrap a function around everything then the global suddenly won't work anymore. Btw, this also won't work if I wrap a function around the function DECLARATIONS. Any ideas, how I could make it work? im using a function which connects to a db called 'comments' and then inside that function i again called another function that will connect to the db 'main' to get avatars.... but as i put Code: [Select] mysql_select_db("main") or die(mysql_error()); on the new function, the original function stops to fetch rows. i tried to remove "mysql_select_db("main") or die(mysql_error());" and used the new function to return some text only and it worked, so i guess the connection to the db was the problem... i tried doing Code: [Select] mysql_query("SELECT * FROM main.avatar INNER JOIN main.list ON main.avatar.title=main.list.id WHERE main.avatar.page_id='$id'"); but it also didnt work I want to define a function instead of repeating query in all my php pages. I call a function by passing an $id value and from that function i have to get all the info related to that id, like name, description and uom.
I am trying to do this, but i dont know how to get these values seperately.
here is my function
function items($item_id) { $details = array(); $result = mysql_query("select item_id, name, uom, description from items where item_id=".$item_id."") or die (mysql_error()); while($row = mysql_fetch_array($result)) { $details[] = array((stripslashes($row['name'])), (stripslashes($row['uom'])), (stripslashes($row['description']))); } return $details; }and i call my function like this $info = items($id);Can somebody guide me in this Hi I am trying to create a hierarchy array from our mysql database. What i have so far is: //instantiate DB & connect $database = new Database(); $db = $database->connect(); //instantiate question object $question = new Question($db); //query $results = $question->read(); //check for data if ($results) { $question_arr['questions'] = array(); $child_arr = array(); while ($row = $results->fetch(PDO::FETCH_ASSOC)) { array_push($question_arr['questions'], $row); $question_arr['questions'][] = buildTree($row); } print_r($question_arr['questions']); } else { echo json_encode(array('message'=>'nothing here!.')); } function buildTree($child) { $branch = array(); foreach ($child as $row) { $childresults = $question->read_children($row['parentid']); while ($childrow =$childresults->fetch(PDO::FETCH_ASSOC)) { $children = buildTree($childrow); if ($children) { $row['children'] = $children; } $branch[] = $childrow; } } //} return $branch; } in my Questions.php file: <?php class Question{ private $conn; public $id; public $childid; public $parentid; public $question; public $pageid; public $numclicks; public $typeid; public $date_created; // Constructor with DB public function __construct($db) { $this->conn = $db; } public function read() { //create query(sql statement) $query = 'SELECT id as parentid, question, pageid, typeid,numclicks,date_created from ct_questions'; // Prepare statement $stmt =$this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } public function read_children($parentid) { //This is from a View I created in Mysql $query = 'SELECT parent_question, parentid, parent_pageid, child_question, childid, child_pageid from ct_vquestion_parent_child_lookup where parentid='.$parentid.''; // Prepare statement $stmt = $this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } }
the current errors i am getting a <br /> <b>Notice</b>: Undefined variable: question in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> <br /> <b>Fatal error</b>: Uncaught Error: Call to a member function read_children() on null in C:\htdocs\api\questions\read.php:41 Stack trace: #0 C:\htdocs\api\questions\read.php(28): buildTree(Array) #1 {main} thrown in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> Hey ive been wanting to know how to make a function call another function which will then create a variable which i can send back to first function where i can use it. I tried somthing like this Code: [Select] <?php a(); function a($wall) { b(); echo $wall; } function b() { $wall = "test"; #a($wall); } ?> Thats what i tried but ofcourse didnt work, how would i go about doing this? Thanks. Is it possible to have a class access another class it its parent directory without using a fully qualified name? While the following script is not valid, it is how I would have thought it would be done should it be possible. If it is not possible, I expect there is a good reason why one would not want to do so, and would appreciate your thoughts why that is so. Thanks // src/PrimaryTopic/SubTopic/SubSubTopic/ParentClass.php namespace PrimaryTopic\SubTopic\SubSubTopic; class ParentClass {} // src/PrimaryTopic/SubTopic/SubSubTopic/Child/ChildClass1.php namespace PrimaryTopic\SubTopic\SubSubTopic\Child; class ChildClass1 extends ..\ParentClass {} // src/PrimaryTopic/SubTopic/SubSubTopic/Child/ChildClass2.php namespace PrimaryTopic\SubTopic\SubSubTopic\Child; class ChildClass2 extends ..\ParentClass {}
Hey Before I start playing around with some code I want to know if it is possible to call a function inside a while loop that will call echo a some stuff then return to the loop it got called by? thanks I have included language file and function file in my index.php
include 'includes/functions.php'; include 'languages/english.php';english.php contains <?php $lang['success']['a'] = 'Settings have been updated.'; $lang['error']['b'] = 'Database error. Please try again later!'; ................................. ?>functions.php <?php function testFunction($id, $settings, $db){ $query = 'UPDATE table_name SET a = a + :a WHERE id = :id'; $update = $db->prepare($query); $update->bindParam(':a', $settings['a'], PDO::PARAM_INT); $update->bindParam(':id', $id, PDO::PARAM_INT); $success = $update->execute(); if($success){ print $lang['success']['a']; }else{ print $lang['error']['b']; } } ................................................. ?>Now if i print testFunction(); i got Undefined variable: lang in ............. If i include 'languages/english.php'; in testFunction() then everything works. Any other way to make $lang working without including language file in testFunction(). (Sorry for my bad english) print testfunction(2, $settings, $db); Hi Everyone. I'm working on a form, that allows the user to select the country / county / area where they are from. I am doing this using: - mysql database store the locations in - PHP OOP, to pull this information from the database - AJAX/Javascript to only show the next dropdown, once the first dropdown has been selected. Example: select country then the county dropdown will appear, select county then the area/town will appear. However, the first drop down for country is placed directly on to the page. So the javascript works fine. but the second dropdown is placed in to a PHP function, and the javascript seems to no longer want to work. CODE: Code: [Select] //////////////// CODE FOR COUNTRY /////////// if(isset($_REQUEST['country'])) { echo ' <div class="labelleft">County / State:</div> <div class="fieldleft"> <div > <select name="county" id="county" onchange="javascript:AJAXQuery("lib/search.php?town="+this.value, "tw", "")"> <option value="0">Select County</option> <option value="0">-------</option>'; $countyList = Area_county::find_country_id($_REQUEST['country']); foreach($countyList as $countyLists){ $county_id = $countyLists->id; $county_list = $countyLists->county; echo '<option value="'.$county_id.'">'.ucwords($county_list).'</option>'; } echo ' </select> </div> </div> <div class="clear"></div>'; } Any ideas? Thanks Hi, I'm an novice/intermediate PHP prgogrammer, so excuse me if this is a stupid question. I have one php program that consist of a few functions. Inside the function taht is the starting point I pickup a few entries from a MYSQL database, and display those in my html page. I wish to dynamically put a link on those entries that makes it possible for the users to click those entries an get directed to other functions inside this very same PHP program WITH a parameter. The parameters that should accompany the url/link into the selected function to be able to select apropriate records from the mysql tables. Any hints and tips for this would be highly appreciated! Kind Regsrds, Terje Hvidsten. I'm using this line a lot on my site. It would be nice if I didn't have to change it 10 times over when I decide to change something. Can I wrap that into a Function and use it in a While loop? echo '<div><a href="/tag/'. strtolower($nameFirst) . '-' . strtolower($nameLast) .'">'. $nameFirst . ' ' . $nameLast .'</a>, '; I have this above it in the While loop.
$nameFirst = $row['nameFirst'];
My function predictably looks like this... function player_name () { echo '<div><a href="/tag/'. strtolower($nameFirst) . '-' . strtolower($nameLast) .'">'. $nameFirst . ' ' . $nameLast .'</a>, '; }
Hi I am trying to use the nl2br function like this while ($row = mysqli_fetch_array($query)) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); echo " <div class='divTableRow'> <div class='divTableCell'>{$row['User']} ;</div> <div class='divTableCell'>nl2br({$row['CommentText']});</div> </div> \n"; } However the output just looks like the attached picture. When I check in the sql db I can see the line breaks when doing a select * from Table ;
I thought this would be fairly straightforward but for some reason isn't working. I have an array built from some MySQL data: - Code: [Select] $all_products[1] = array( "title"=>"widget", "product_code"=>"wid-123", "colour"=>"blue"); $all_products[2] = array( "title"=>"thingy", "product_code"=>"thi-345", "colour"=>"red"); This works fine when used like: - echo 'Product #1 is a ' . $all_products[1]['colour'] . $all_products[1]['title'] . ', code: ' . $all_products[1]['code']; Gives: "Product #1 is a blue widget, code: wid-123" However, if I do this: - function showproductinfo($thisproduct) { echo 'Product #' . $thisproduct . ' is a ' . $all_products[$thisproduct]['colour'] . $all_products[$thisproduct]['title'] . ', code: ' . $all_products[$thisproduct]['code']; } showproductinfo(1); It gives nothing Can I use a variable passed via a function as the array key in this way? If so, how? And if not, what's the best way to do what I, trying to do? hello. i have two functions that are not working because i cant seem to input the php and java correctly.. could someone help please. how do i put these lines into a function: 1 - Code: [Select] function applyBox() { echo ' <div id="apply"> <h3><b><span class="arial18_GRN">Apply NOW</span> to become a<br>BusinessMobiles.com Affiliate</b></h3> <p class="applyText">Drive quality traffic to one of our<br>partners and get paid for it.</p> <a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Apply','','image/callsToAction/applyButton2.jpg',1)"> <img src="image/callsToAction/applyButton1.jpg" class="applyButton" alt="Apply" name="Apply" width="137" height="36" border="0"></a> </div> '; } this part is not working: onMouseOver="MM_swapImage('Apply','','image/callsToAction/applyButton2.jpg',1)"> i can see that the ' is breaking it. i tried putting .'s but it didn't work : onMouseOver="MM_swapImage('.Apply.','..','.image/callsToAction/applyButton2.jpg.',1)"> 2 - this form: Code: [Select] <div class="form"> <form name="Form" method="post" action="<?PHP echo $_SERVER['PHP_SELF']; ?>"> <input name="submit" type="hidden" value="submit" /></input> <input type="text" class="inputField" name="Uname" id="Uname" value="'.$Uname.'" onfocus="clearUname()"></input> <input type="text" class="inputField" name="PW" id="PW" value="'.$PW.'" onfocus="clearPW()"></input> <input type="image" class="submit" src="image/wrapper/submit.jpg" value="Submit" alt="login" width="36" height="20" border="0" /></input> </form> this part is not working : <form name="Form" method="post" action="<?PHP echo $_SERVER['PHP_SELF']; ?>"> i tried: <form name="Form" method="post" action="'.echo $_SERVER['PHP_SELF'].'"> but no luck. any suggestions ???? thanks ricky I have the array defined and print_r (outside the function is show what I need...) However, I need to somewhay pass those three arguments - name, price, shipping (keys & values) into the "all_products" function and assign (inside the function) each element to a variable {name, price, shipping}. Code: [Select] function all_products($key,$value) { # This is where I'm lost - I know the values are passed to the function but how to I assign them to below variable? echo "$name"; echo "$price"; echo "$shipping"; // Products array defined to send values into "all_products" function & loop to display item name & individual pricing (using WHILE LOOP) $products = array('Product1' => array ( 'name' => 'item one', 'price' => '30.00', 'shipping' => '0.00'), 'Product2' => array ( 'item two', 'price' => '19.50', 'shipping' => '0.10'), 'Product3' => array ( 'item three', 'price' => '21.99', 'shipping' => '0.10') ); while (list($keys, $values) = each($products)) { while (list($k, $v) = each($values)) echo "Checking Looped Data Outside Function: <strong>$k: </strong> $v<br/>"; # echo "<pre>"; # print_r($value); # echo "</pre>"; # Trying to send array elements into "all_products" function & echo (name, price, shipping) keys and values inside that function all_products($k,$v); } I need $row['con_id'] outside the function so I can put it into a query, but simply putting global in front of it won't work. What would be the right way to do? This portion of code is INSIDE a function: //Loop through the array of data while ($row = mysqli_fetch_array ($data)) { echo "<table padding='0' margin='0' class='knuffixTable'>"; echo "<input type='hidden' name='con_id' value='<?php echo " . $row['con_id'] . "; ?>' />"; echo "<tr><td width='65px' height='64px' class='avatar_bg' rowspan='2' colpan='2'><img src='$avatar_path' alt='avatar' /></td><td class='knuffix_username'><strong>" . $user_name; echo "</strong><br />" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . "</td></tr><tr><td>"; echo "<form action='' method='post'> <input type='submit' name='plusVote' value='Y' /> <input type='submit' name='minusVote' value='N' /> </form></td><td class='votes'>Y[ - ] | N[ - ]</td></tr>"; echo "<tr><td class='knuffix_name' colspan='3'><strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td colspan='2' class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "</table>"; The PHP documentation does not show any examples how to GLOBALIZE a mysqli function. I'd need a way to use $row['con_id'] outside the function for the voting script I'm writing. Thanks for the suggestions. |