PHP - Use One Variable Value In Another Variable Under Same Class
Hi,
I have following code : Code: [Select] <?php class CategoryWork { public $form = ""; public $error = ""; public $add_form = "<br /><br /><p><strong>Add New Category</strong></p><br /><form id=\"form1\" name=\"form1\" method=\"post\" action=\"category.php?action=add\"> <table width=\"550\" height=\"170\" border=\"0\"> <tr> <td width=\"153\">Name :</td> <td colspan=\"2\"><label for=\"cat_name\"></label> <input name=\"cat_name\" type=\"text\" id=\"cat_name\" size=\"50\" maxlength=\"50\" /></td> </tr> <tr> <td>Slug :</td> <td colspan=\"2\"><label for=\"cat_slug\"></label> <input name=\"cat_slug\" type=\"text\" id=\"cat_slug\" size=\"50\" maxlength=\"50\" /></td> </tr> <tr> <td>Description</td> <td colspan=\"2\"><label for=\"cat_desc\"></label> <textarea name=\"cat_desc\" id=\"cat_desc\" cols=\"48\" rows=\"10\"></textarea></td> </tr> <tr> <td> </td> <td width=\"97\"><input type=\"submit\" name=\"button\" id=\"button\" value=\"Submit\" /></td> <td width=\"286\"><input type=\"reset\" name=\"button2\" id=\"button2\" value=\"Reset\" /></td> </tr> <tr> <td> </td> <td colspan=\"2\">error</td> </tr> </table> </form>"; } ?> At the line of <td colspan=\"2\">error</td> I want to insert $error, hence I made the line as <td colspan=\"2\">".$error."</td> and also tried <td colspan=\"2\">".$this->error."</td> After executing with this, php says syntax error at the line of public $add_form I am going to declare an error at the $error When I do <td colspan=\"2\">$error</td> it says : Parse error: syntax error, unexpected '"' at line of public $add_form When I do <td colspan=\"2\">".$error."</td> it says : Parse error: syntax error, unexpected '.', expecting ',' or ';' at the above line i.e. of <td> I am damn confused, I googled but nothing found any helpful material. Anybody please help me.. Thanks Similar TutorialsI have a class that creates a grid from an xml feed. The class file is attached. The grid displays on a page which is defined within the class as follows: Code: [Select] private $results_page = '/foobar.php'; I'm including the same class in multiple folders (the folders are addon domains) so I can have just one copy of the class so it is easy to modify. The problem is that I need to add a variable containing the folder name to the $results_page path, so that when the class executes within each folder, the $results_page is 'FOLDER//foobar.php' I have a file with defines in each folder, and I have tried including that file in the class and using the defined var in the construct, but I can't get it to work. What am I missing? Code: [Select] class replayer extends users { --SNIP-- public $islive = false; --SNIP-- function chat($id, $nick, $chat) { --SNIP-- <----------- } } There's my code, I want to take the variable $islive from the above class and use it in the chat() function. How would I do it? I've tried making it a global inside of the chat() function. If i declare protected variable in a class how can i access those variable in other class inheriting that class? Can anyone post example code? I am working on a site that was made a while ago and on a custom page I am making I am needing to call up variables and my brain is too fried to think up the solution for this. The standing code is this: class site{ var $name = 'Site'; var $data = 'on'; { What I need to do is callup the variables, such as $name, as simple as possible. How would I do this? I have a method that is returning a funny variable, it should be returning what is below and when I echo the return from inside the method it is right. Code: [Select] Software/Section but when I goto echo the from outside the class I get the following. It adds a back slash Code: [Select] Software//Section this is the method code and it works fine when I echo the returnValue the value is right Code: [Select] // Creates a dymamic case statement for making a the choice // inside and array foreach (scandir($dir) as $folderItem) { if ($folderItem != "." AND $folderItem != "..") { if (is_dir($dir.$folderItem.DIRECTORY_SEPARATOR)) { $folderItem = $folderItem ; // this allows the the dir to be placed if statements below $folderContents = $this->showPage( $dir.$folderItem ,$getPageGlobal , $subdir); $subdir = ""; // this resets so that ithe value does not get added to main links; } else { // put into if into array if($getPageGlobal== $folderItem) { $pageReturn = $dir . $folderItem; } } } } echo $pageReturn.'<br>'; return $pageReturn; This is the way I am echoing the class. This is when it decides to add the back slash Code: [Select] echo $dynamicMenu->getShowPage(); Using this locally works fine: $html = $name::add_content($name, $html); but i get the double colon error whe using it live. $name is a name of a valid class. What could throw this error when it works locally? Hello I want to be able to change the class depending on if a variable is 1 or 0. <html> <p class="note-general"> This is the general </p> <p class="note-warning"> And this is the warning </p> </html> I want the variable $adult (that can be 1 or 0) to set if the class should be a note-general or note-warning. Thank you for support I have this as my autoloader. All the classes are based off of Class O. I wanted to be able to do something like $dog = new Dog(); even if I hadn't yet created Dog.class.php and made it extend O. (I realize there are plenty of reasons this is a bad idea, this is a temporary part of the project, I am just trying to get a few things set up and thought it would work - now I'm probably going to spend more time trying to do this than it would have saved, but I'm curious. ) ( ! ) Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in C:\wamp\www\project\index.php on line 22 (line 22 is Class $class_name extends O{ Code: [Select] <?php function autoload($class_name) { if(file_exists($class_name.'.class.php')){ require_once($class_name.'.class.php'); }else{ Class $class_name extends O{ } } } ?> Is it possible to do what I'm trying to do? Hello, I am creating a class which contains one private function that deals with connecting to a SQL Server and executing the sql that is passed in to that function. I have defined a class variable which is assigned the value of sqlsrv_query like so. $this->QueryResult = sqlsrv_query($conn,$sql); I have placed private $QueryResult at the top of my class. The other public methods call this private function to assign the result set to the class variable, the private method returns and then the public methods loop through the results array like so. while($row = sqlsrv_fetch_array($this->QueryResult)) .. but the while loop never gets entered. If I declare everything in the same method then it works, however there are going to be several public methods that will use this private method and I don't want to duplicate all the database coding. Hope someone can help Hi, when i extend a class containing a private variable and then access the variable in the extended class it doesn't produce any error and works fine and when i access the variable using the object of the extended class it works even then, i think private variable should not be accessable in an extended class neither by object of that extended class here is the code <?php class textbox{ var $body_text, $body_text1; private $body_private="this is private value"; protected $body_protect="this is protected value"; function __construct($text_in, $text_out){ $this->body_text=$text_in; $this->body_text1=$text_out; } function display(){ echo "$this->body_text<br>"; echo "<i>"; echo "$this->body_text1</i><br>"; echo "$this->body_private<br/>"; echo "$this->body_protect<br/>"; } function test_new(){ echo "see if this private echo works"; } } $box=new textbox("any new value","any old value" ); $box->display(); $box->body_text="this is public thats why i can access it"; $box->body_text1="this is public thats why i can access it"; /*$box->body_private="this is private value changed"; //you will see we can't access the private and protected memebers from outside $box->body_protect="this is protected value changed"; */ $box->display(); $box->test_new(); class textboxbold extends textbox{ function __construct($text_on, $text_off, $text_get, $text_go) {$this->body_text=$text_on; $this->body_text1=$text_off; $this->body_protect=$text_get; $this->body_private=$text_go; } function display(){ echo "<b>$this->body_text</b><br>"; echo "<b>$this->body_text1</b><br>"; echo "<b>$this->body_protect</b><br>"; echo "<i>$this->body_private</i><br>"; } } $boxnew=new textboxbold("new Bold text", "text in bold","protected member","private"); $boxnew->display(); $boxnew->body_private="this is simple text taken from outside"; $boxnew->display(); $boxnew->test_new(); ?> please recommend, is it working as it should be I have a class that I created, halfway down my page I call a function from the class which prints some code and also changes a variable inside the class. It's a search class basically it prints out the search results and saves the total amount of results into the variable. I want to display the amount of results above the results like so:- echo $Search->results; $Search->GetResults('foo'); The problem is that $Search->results will be equal to NULL until the variable is updated in the function GetResults. Hope that makes sense, am I going about this wrong? I have the following simple class: Code: [Select] class Settings { public static $mysql_datetime_format = "%c/%e/%Y %l:%i %p " . date("[T]"); } And referencing like: Code: [Select] echo Settings::$mysql_datetime_format; But, I am getting the error: Parse error: syntax error, unexpected '.', expecting ',' or ';'. Why is this invalid? hello all, i have ran into another issue i get this message when i go onto my homepage Notice: Undefined variable: layout in i have the following includes on the main index page: Code: [Select] <?php // Include Main Core File. include '_class/core.php'; // Include Config File include 'config/config.php'; include 'config/db.php'; // Use Database $obj->connect(); // Include library include '_class/library.php'; // Include layout include 'layout/index.php'; ?> on the config file i have the varible it is refering too: Code: [Select] <?php $layout = $url . "layout/"; ?> the actual file i get the error on (library.php) Code: [Select] <?php class library extends core { function advert() { /* * Name your images 1.jpg, 2.jpg etc. * * Add this line to your page where you want the images to * appear: <?php include "randomimage.php"; ?> */ // Change this to the total number of images in the folder $total = "2"; // Change to the type of files to use eg. .jpg or .gif $file_type = ".png"; // Change to the location of the folder containing the images $image_folder = $layout . "layout/images/adverts"; // You do not need to edit below this line $start = "1"; $random = mt_rand($start, $total); $image_name = $random . $file_type; echo "<img src=\"$image_folder/$image_name\" alt=\"$image_name\" />"; } } $obj = new library; ?> is there a way to make it so it $layout works on any page or file as long as its in the includes? thanks again. Currently, I'm trying to write a contact form, and perhaps I'm overcomplicating it, but I have a public variable called $EquationAnswer that stores the answer to the Captcha method (randomised maths question) and whenever the page reloads, it creates a new instance of the Contact class, which then erases the value that has been stored in that variable.
What I'm trying to achieve is keeping the value stored even after a new instantiation of the class. I remember from a class at University that static was a way to do this, but this was in C#.
<?php class Contact { public $EquationAnswer; public function CaptchaCreation() { $SignArray = array('+', '×', '-'); $NumberOne = rand(1, 9); $NumberTwo = rand(1, 4); if($NumberOne < $NumberTwo) $SignIndex = rand(0, 1); else $SignIndex = rand(0, 2); $Sign = $SignArray[$SignIndex]; $EquationString = $NumberOne." ".$Sign." ".$NumberTwo; switch($Sign) { case "+": $Answer = $NumberOne + $NumberTwo; break; case "-": $Answer = $NumberOne - $NumberTwo; break; case "×": $Answer = $NumberOne * $NumberTwo; break; } $this->EquationAnswer = $Answer; return $EquationString; } public function EchoContactForm() { $CaptchaMessage = $this->CaptchaCreation(); echo "<form method='POST' action=''>\n\n"; echo "\t\t\t\t\t<table>\n\n"; echo "\t\t\t\t\t\t<tr><td>Name: </td><td><input type='text' name='name' /></td></tr>\n"; echo "\t\t\t\t\t\t<tr><td>Email: </td><td><input type='text' name='email' /></td></tr>\n"; echo "\t\t\t\t\t\t<tr><td>Subject: </td><td><input type='text' name='subject' /></td></tr>\n"; echo "\t\t\t\t\t\t<tr><td>Message: </td><td><textarea rows=5 name='message'></textarea></td></tr>\n"; echo "\t\t\t\t\t\t<tr><td>What is: ".$CaptchaMessage."?</td><td><input type='text' name='captcha' /></td><td></td></tr>\n"; echo "\t\t\t\t\t\t<tr><td colspan=2 style='text-align: right'><input type='submit' name='submit' value='Send' /></td></tr>\n\n"; echo "\t\t\t\t\t</table>\n\n"; echo "\t\t\t\t</form>\n"; } public function ContactFormValidation($Name, $Email, $Subject, $Message, $CaptchaInput, $CaptchaAnswer) { echo $CaptchaAnswer; $ErrorsArray = array(); if(strlen($Name) == 0) array_push($ErrorsArray, "You must provide a name."); if(strlen($Email) == 0) array_push($ErrorsArray, "You must provide an email."); if(strlen($Message) == 0) array_push($ErrorsArray, "You must provide a message."); if(strlen($CaptchaInput) == 0) array_push($ErrorsArray, "You must provide an answer to the maths question."); if($CaptchaInput != $CaptchaAnswer) array_push($ErrorsArray, "Incorrect captcha answer."); if(count($ErrorsArray) > 0) { echo "There are ".count($ErrorsArray)." Errors: <br />"; foreach($ErrorsArray as $E) echo $E."<br />"; } else { return true; } } } ?>^ That's the Contact class, and the main function that I want to focus on is the last one, "ContactFormValidation()". From the contact form page (which is within a template), I want it to send the EquationAnswer variable to that function so that it can compare what the user has input. <?php //Instantiate the contact class include './inc/PHP/classes/ContactClass.php'; $ContactClass = new Contact; if(!isset($_POST['submit'])) { $ContactClass->EchoContactForm(); } else { $NameInput = $_POST['name']; $EmailInput = $_POST['email']; $SubjectInput = $_POST['subject']; $MessageInput = $_POST['message']; $CaptchaInput = $_POST['captcha']; $CaptchaAnswer = $ContactClass->EquationAnswer; //Tried echoing out what is in the variable but it produces nothing because the contact class is a new instance. //echo $CaptchaAnswer; if($ContactClass->ContactFormValidation($NameInput, $EmailInput, $SubjectInput, $MessageInput, $CaptchaInput, $CaptchaAnswer) == true) { //Mail function } } ?>Any help would be appreciated. Cheers. I tried these below, Code: [Select] class Site extends Controller { function Site() { public $data = Array(); } } but it fail? Thanks in advanced. I'm having a problem with (what I'm almost certain is) variable scope, maybe you can help... So I've got a parent class that, among other things, gets the name of the filepath, explodes this filepath, checks for files with names that mirror that filepath (without the slashes of course), and includes them if they exist: class ParentClass { public $RootFolder; public $PageSections; function __construct() { global $root_folder; $this->RootFolder = $root_folder; //get all directory names... $cleanse = $this->RootFolder; $pagepath = str_replace($cleanse, '', dirname($_SERVER['PHP_SELF'])); $this->PageSections = explode('/', $pagepath); } function RequireIfExists ($sections, $root_folder, $file_name, $file_type) { foreach ($sections as $i){ if (isset($o)) { $i = $o."/".$i; } $file = $root_folder.$i."/".$file_name.$file_type; if (file_exists($_SERVER['DOCUMENT_ROOT'].$file)) { require ($_SERVER['DOCUMENT_ROOT'].$file); echo "<!--".$file." included -->"; //temporary measure to ensure that the file is at least being called. } $o = $i; } } // so, excuting the function // $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); // on some/sub/folder/index.php // will look for somesectionvars.php, somesubsecitonvars.php & somesubfoldersectionvars.php // and include whichever ones exist. } Then there is a child class that utilizes this function, and successfully requires the file. I know the file is coming through because the echo statement on the page shows up in the code, but I cannot get the variables to pass through? <?php class HtmlHead extends PageBlock{ public $PageKeywords; public $PageDescription; public $PageStyles; public $PageScripts; //------------------------ public $SectionKeywords; public $SectionDescription; //------------------------ public $SiteKeywords; public $SiteDescription; public $SiteStyles; public $SiteScripts; //------------------------ public $CatchAll; function __construct() { parent::__construct(); //$this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //I have tried calling the function here with no luck global $site_description, $site_keywords, $section_description, $section_keywords, $xyz; //also made sure to global the variables from the required page $this->SiteDescription = $site_description; $this->SiteKeywords = $site_keywords; $this->SectionDescription = $section_description; $this->SectionKeywords = $section_keywords; $this->PageDescription = $page_description; $this->PageKeywords = $page_keywords; } function Constructor() { $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //Tried calling the function here as well, no luck global $xyz; //global'd the var i want echo "\n<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; echo "\n<!--Sec Keywords are".$xyz."-->"; //Tried to echo the var... //------------------------Rest of code... } } And here is the page that is being required... <?php echo "<!-- 1234 1234 1234 1234 -->"; //test measure to see if/where file is including $section_keywords = "red, secondary"; $section_description = "this is the red section description"; $xyz = "1234"; //test Var to see if there was a naming conflict with the above two.. ?> What am I overlooking this time? I am trying to allow the user to update a variable he chooses by radio buttons, which they will then input text into a box, and submit, to change some attributes. I really need some help here. It works just fine until I add the second layer of variables on top of it, and I can't find the answer to this question anywhere. <?PHP require('connect.php'); ?> <form action ='' method='post'> <select name="id"> <?php $extract = mysql_query("SELECT * FROM cars"); while($row=mysql_fetch_assoc($extract)){ $id = $row['id']; $make= $row['make']; $model= $row['model']; $year= $row['year']; $color= $row['color']; echo "<option value=$id>$color $year $make $model</option> ";}?> </select> Which attribute would you like to change?<br /> <input type="radio" name="getchanged" value="make"/>Make<br /> <input type="radio" name="getchanged" value="model"/>Model<br /> <input type="radio" name="getchanged" value="year" />Year<br /> <input type="radio" name="getchanged" value="color" />Color<br /><br /> <br /><input type='text' value='' name='tochange'> <input type='submit' value='Change' name='submit'> </form> //This is where I need help... <?PHP if(isset($_POST['submit'])&&($_POST['tochange'])){ mysql_query(" UPDATE cars SET '$_POST[getchanged]'='$_POST[tochange]' where id = '$_POST[id]' ");}?> Hello all. I am very new to PHP, and I am not sure where to look or what I'm looking for in my current assignment. My task is to take in two numbers between 0-100. Once I take in that number, it should state beside it "The __ was accepted." The program should not accept any numbers greater than 100 or any characters. Once I do this, I must take a second number and do a similar thing. Finally, I must have a statement show up at the bottom stating which number is greater. Essentially, I need help in determining what I should use to place parameters, and how I can keep the program from echo ing any statement until input has been taken and tested for parameters. Any help you can provide will be greatly appreciated! I have just re-installed Xampp and suddenly my sites are now displaying lots of: Notice: Use of undefined constant name - assumed 'name' in ... Notice: Use of undefined constant price - assumed 'price' in ... this is an example of the line its refering too: $defineProducts[1001] = array(name=>'This is a product', price=>123); My login script stores the user's login name as $_SESSION[ 'name'] on login. For some unapparent reason, i'm getting errors stating that $user and $priv are undefined variables, though I've attempted to define $user as being equal to $_SESSION['name'], using $user to look up the the user's privilege level (stored as the su column ) in the SQL table, and then where the result of the sql query is $priv which is then evaluated in an if statement. I can't seem to figure out why this might not be working. The code I'm using: <?php session_start(); function verify() { //verify that the user is logged in via the login page. Session_start has already been called. if (!isset($_SESSION['loggedin'])) { header('Location: /index.html'); exit; } //if user is logged in, we then lookup necessary privleges. $_SESSION['name'] was written with the login name upon login. Privleges // are written in db as a single-digit integer of of 0 for users, 1 for administrators, and 2 for special users. $user === $_SESSION['name']; //Connect to Databse $link = mysqli_connect("127.0.0.1", "database user", "password", "database"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } //SQL Statement to lookup privlege information. if ($result = mysqli_query($link, "SELECT su FROM accounts WHERE username = $user", MYSQLI_STORE_RESULT)) { //LOOP TO CYCLE THROUGH SQL RESULTS AND STORE Privlege information as vairable $priv. while ($row = $result->fetch_assoc()) { $priv === $row["su"]; } } // close SQL connection. mysqli_close($link); // Verify privleges and take action. Only a privlege of "1" is allowed to view this page. A privlege of "2" indicates special //accounts used in other scripts that have certain indermediate additional functions, but are not trusted administrators. if ($priv !== 1) { echo $_SESSION['name']; echo "you have privlege level of $priv"; echo "<br>"; echo 'Your account does not have the privleges necessary to view this page'; exit; } } verify(); ?>
|