PHP - Decalring Vars / Default Values
What is the difference between declaring values at the top of a class versus in between the parenthesis of a method?
Class MyClass { private $table = 0; public $field = "name"; // etc... Class MyClass { private $_table; public $field; public function myFunction($_table=0, $field="name") {} Similar TutorialsThis topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=352519.0 I sometime pass configuration settings as an associate array... public function __construct(JsonValidatorMethods $methods, array $options) { foreach($options as $option) { //validate whether valid and if so set $this->$option. Options not provided will default to their private $strictMode=true value } } $validator=new JsonValidator($methods, ['sanitize'=>true, 'strictMode'=>true, 'setDefault'=>false]); And other times pass them as individual arguments... public function __construct(JsonValidatorMethods $methods, bool $sanitize=false, bool $strictMode=false, bool $setDefault=true) {} $validator=new JsonValidator($methods, true, true, false); I have a class which I was doing the later and also which I wish to allow them to be first set in the constructor but also specified when calling some of the public methods. It became a pain to pass all the individual flags to each private method, so I thought I would give bitmask constants a try as shown below. I recognize that this approach only allows booleans to be passed, but I am okay with this. The part I am not sure about is how best have default values. For instance, maybe the default is $this->options=0b0110, 0b1100 is passed to the constructor, and 0b1 (aka 0b0001) is passed is passed to the public method. The high three bits in 0b0001 just are not provided, but how can I not interpret them as explicitly false? Also, a little off topic, but am I implementing this bitmask approach correctly, and any strong options whether one of these three approaches or some totally other approach is best? Thanks class JsonValidator { //Use provided options const SANITIZE = 0b0001; //Whether to sanitize (i.e. 'false' is changed to false) const STRICTMODE = 0b0010; //Currently only enfources that boolean is true/false (instead of 1/0 or "true"/"false") const SETDEFAULT = 0b0100; //If true, type double and value "nan" will be converted to 0, etc. private $methods, $options; static public function create(int $options=0):self { return new self(new JsonValidatorMethods, $options); } static public function getOption(array $options):int { $o=0; foreach($options as $option) { if(!defined("self::$option")){ throw new JsonValidatorErrorException((is_string($option)?$option:'given constant').' is not valid'); } $o=$o|constant("self::$option"); } return $o; } public function __construct(JsonValidatorMethods $methods, int $options=0) { $this->methods=$methods; $this->options=$options; } public function validate(array $input, array $rules, int $options=0){ $options=$options|$this->options; if($options & self::SANITIZE) { $value=$this->sanitize($input, $rules, $options); } } private function sanitize(array $input, array $rules, int $options=0){} } $validator=new JsonValidator($methods, JsonValidator::SANITIZE|JsonValidator::SETDEFAULT); Edited June 27, 2019 by NotionCommotion Nevermind => Maybe I should start my constants with high bit set such as const SANITIZE = 0b1000; This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=316203.0 I am inplanting a bonus system to a game i have. I want to say at first that i am not good at php am reading alot and go by learn by doing. But after a few hours i kinda gave up. Here is the code. The page end up blank. And i tested so my syntax work $cost and $points with only the db stuff and this code <div class="yellow_12_bold"><? print (number_format($points)); ?> </div> <div class="yellow_12_bold"><? print (number_format($cost)); ?> </div> And it does. Anyway here is the code Code: [Select] <? $dbq = $db->execute("select * from Bonus where username='$username'"); $points = $dbq->fields['points']; $allpoints = $dbq->fields['points_total']; $dbq->close(); if ($cost == "5" && $amount == "3000") { if ($points == "5" || $points > "5") { $sqlb = "update UserData set turns=turns+'3000' WHERE turns < 50000 and location != '9' and frozen = '0'"; $result1 = mysql_query($sqlb); $sqlc = "update Bonus set points=points-'5' WHERE username = '$username'; $result2 = mysql_query($sqlb); $points2 = ($points - 5); <p align="center" class="black">Thank you! 3000 turns have been added to everyone. You have <div class="yellow_12_bold"><? print (number_format($points)); ?> </div> bonus points left. </p> } else { <p align="center" class="black">Sorry you dont have $cost points. You have <div class="yellow_12_bold"><? print (number_format($points)); ?> </div> bonus points left.</p> } } ?> hi phpfreaks I am trying to remove the get variables from my url. the code below works if I echo it out but to try to modify the $_server variable it will not work. Any ideas? Code: [Select] $current_url = explode('?',$_SERVER["REQUEST_URI"]); $_SERVER["REQUEST_URI"]= $current_url[0]; echo $current_url[0]."<br>"; Trying to pass VARS $URL1 and $type to header location.Heres the code. Code: [Select] $URL1 = $_POST['url']; $type = $_POST['type_request']; session_start(); $string = strtoupper($_SESSION['string']); $userstring = strtoupper($_POST['userstring']); session_destroy(); if (($string == $userstring) && (strlen($string) > 4)) { header("Location: $success"); exit(); The VARS come from a FORM and then go to this script for checkind data. I need to have them continue to the next page. hey guys i have a static attribute $_exception_handler which is set to Exception and....now this value could change to a customer exception_handler but what i want to do is <?php catch (self::$_exception_handler $e) { } but im getting an error...is there a way of doing this...any help would be greatful thanks class below <?php class Autoloader { protected static $_exception_handler = Exception; protected static $_classes = array(); public static function load_library($class_name) { $file = ROOT . DS. LIBRARY_DIRECTORY . DS . $class_name . CLASS_EXTENSION; try { self::load_class($class_name, $file); } catch (self::$_exception_handler $e) { echo $e->getMessage(); } } public static function load_exception($class_name) { } public static function load_class($class_name, $file) { if (!class_exists($class_name, FALSE)) { if (file_exists($file)) { require_once $file; } else { throw new Exception(sprintf('Class %s not found.', $class_name)); } } } } Sorry if this isn't the right forum, I wasn't sure where to post this. Alright, so I have a high score submit script, and it goes as follows... This is the actionscript: Code: [Select] on (release) { var usco LoadVars = new LoadVars(); uscore.name = _root.suname; uscore.score = _root.suscore.stime; uscore.game = "alien"; uscore.mode = "survival"; uscore.sendAndLoad("linkhere", uscore, "POST"); play(); } Note: We have also tried: Code: [Select] on (release) { var usco LoadVars = new LoadVars(); uscore.name = _root.suname; uscore.score = _root.suscore.stime; uscore.game = "alien"; uscore.mode = "survival"; var uscoresubmit:LoadVars = new LoadVars(); uscore.sendAndLoad("linkhere", uscoresubmit, "POST"); play(); } The PHP is: <?PHP include('Connect.php'); $name=$_POST['name']; $name=mysql_real_escape_string($name); $score=$_POST['score']; $score=mysql_real_escape_string($score); $game=$_POST['game']; $game=mysql_real_escape_string($game); $mode=$_POST['mode']; $mode=mysql_real_escape_string($mode); if(!empty($game)) { mysql_query("INSERT INTO scores(game, name, score, mode) VALUES ('$game', '$name', '$score', '$mode')"); } ?> I have also tried running a number of things on the "else" of that if(!empty($game)) and nothing has pulled through, so I'm under the notion that it isn't loading the page in sendAndLoad()? It was working before, but it appears to have just stopped, we're not sure what we changed. Any help would be greatly appreciated! Thanks, Xyphon Hi! I'm working on a simple e-commerce script. I have some $_SESSION variables that is defined and works fine while surfing on the site. But when I close the browser and reenter the site, all the session-variables are not defined (unset?), until i click on a link on the site. Weird behavior... please help! /I I want to use all five results separately in order to use in a Jquery slider. Code: [Select] <?php $a = "SELECT * FROM blog_posts ORDER BY id DESC LIMIT 5"; $query = mysql_query($a) or die (mysql_error()); $query_results = mysql_fetch_array($query); ?> I know if i was going to grab vars from an normal array i would just use... Code: [Select] <?php echo $array_reults['0'] ?> Can any one help me with this problem? Hi I am attempting to request a single row from a table that has 20 fields. I want to turn each field into it's own variable (you'll see oc1, oc2 etc in the code) and then echo the variable just to check it has worked. When I run the qry below - it picks up the first one correctly but then places the same value in all the other fields. (The $question var should be a long text string but is echoing the first variable instead. There's clearly something wrong with the way I have constructed this - but I don't know at which point it has gone wrong. Can anyone help? $result = mysql_query("SELECT oid,qid,question,posneg,oc1,oc2,oc3,oc4,oc5,oc6,oc7,psc1,psc2,psc3,psc4,psc5,psc6,psc7,psc8,psc9 FROM tblquestions WHERE oid = '1'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $oid=mysql_result($result,"oid"); $qid=mysql_result($result,"qid"); $question=mysql_result($result,"question"); $posneg=mysql_result($result,"posneg"); $oc1=mysql_result($result,"oc1"); $oc2=mysql_result($result,"oc2"); $oc3=mysql_result($result,"oc3"); $oc4=mysql_result($result,"oc4"); $oc5=mysql_result($result,"oc5"); $oc6=mysql_result($result,"oc6"); $oc7=mysql_result($result,"oc7"); $psc1=mysql_result($result,"psc1"); $psc2=mysql_result($result,"psc2"); $psc3=mysql_result($result,"psc3"); $psc4=mysql_result($result,"psc4"); $psc5=mysql_result($result,"psc5"); $psc6=mysql_result($result,"psc6"); $psc7=mysql_result($result,"psc7"); $psc8=mysql_result($result,"psc8"); $psc9=mysql_result($result,"psc9"); ?> <?php echo $oid; // Question Number?> <?php echo $qid; // Question Number?> <?php echo $question; // Question Number?> <?php echo $posneg; // Question Number?> <?php echo $oc1; // Question Number?> <?php echo $oc2; // Question Number?> <?php echo $oc3; // Question Number?> <?php echo $oc4; // Question Number?> <?php echo $oc5; // Question Number?> <?php echo $oc6; // Question Number?> <?php echo $oc7; // Question Number?> <?php echo $psc1; // Question Number?> <?php echo $psc2; // Question Number?> <?php echo $psc3; // Question Number?> <?php echo $psc4; // Question Number?> <?php echo $psc5; // Question Number?> <?php echo $psc6; // Question Number?> <?php echo $psc7; // Question Number?> <?php echo $psc8; // Question Number?> <?php echo $psc9; // Question Number?> Alrite, i have a configs.php that holds a bunch of information (Login info mostly) and when i do $UsrNme = $_POST["user"]; $Passw = $_POST["pass"]; include 'configs.php' if ($UsrNme == $UserName && $Passw == $Password) { setcookie("User", "True", time()+3600); echo "Welcome {$UsrNme}; You have been successfully logged in!"; } else { echo "Sorry, the username {$UsrNme} was not successfully logged in."; } It prints my configs.php instead of using the variables $UserName and $Password to check against UsrNme and Passw... Am i doing something wrong or is this supposed to happen? Hi all If there a better way of setting variables within classes than taking it through the __construct and setting via $this ?? e.g. class SectionsConnect { protected $var; public function __construct($var){ $this->var= $var; } } Can you not set the variable automatically as it comes in through the __construct? Thanks Magnetica Hello Guys, I want to be able to filter out any url in any of form $_POST vars? Would I do it with a foreach loop and the preg replace function? I would consider any web address in my form spam. I would like to filter it out.. I'm already using Strip tags, htmlentities, strip_tags, stripslashes & mysql_real_escape_string but they don't seem to filter out URLs.. Thanks for your help in advanced.. Hello, I have been studying PHP for less than a year so please be gentle. I am building an agency website where users can add themselves etc. What I want to do now is allow clients to collect a list of these users which they can submit to the site along with a job description. What I actually need help with is sending the usernames to a 'collection' page. I want to allow the client to move between the profile pages selecting the users they like the look of and then be able to go to the 'cart/collection' page and see their list. I have a basic knowledge of sessions just no real idea how to pass variables/arrays. Any help would be much appreciated. Cheers - Lee. Hi, In my ErrorDocument I'd like to be able to set some variables for future use then redirect using header() and access them. .htaccess has this entry in it: ErrorDocument 404 /error.php I can pass variables in cookies and all works: setcookie('my_var', 'my_val'); header ("Location: $url"); I would rather set $_SESSION variables but I can't get it to work. session_start(); $_SESSION['my_var'] = 'my_val'; header ("Location: $url"); then... echo $_SESSION['my_var']; returns "". This works fine from other php scripts but not from ErrorDocument. What am I doing wrong here? .htaccess has this in it: ErrorDocument 404 /error.php TIA. Alright, so I am writing a script for a secretary to do some data entry. With this script there is a few file upload fields, now depending on the item entered not all fields need to be filled out. Therefore, the SQL statement will change depending on whether or not that field was filled out. Should I just use IF statements to check too see if the POST var was sent, then change the statement accordingly, or would there be a more productive way? Thanks for any feedback.. Hello, I am having an issue where PHP nulls the donation amount after multiple form submits. Here is a synopsis of what is happening. 1: User enters donation amount and clicks 'submit' 2: Is taken to a confirmation page where they must agree to terms 3: User fails to agree to the terms, the page is reloaded with an error message, and the donation amount is set to null I want to make the donation amount display despite multiple confirm page reloads. How would I do this? Here is the site to test it yourself. Ignore the steamid input and check "do not change my rank upon donation" to test. http://forums.stgdarkrp.org/donate2/check.php Please note: If you use IE, the formatting is messed up, that is a problem I will look into later Hey guys, OK, heres what I would like to do. On my form, I have 50+ variables and not all of them require a response. If inserted, they insert a blank in the DB, instead of NULL. First, does this even matter? If it does, how can I create a function that checks the var to see if its empty, and if empty $var = NULL; Thanks Hi there, Need a little help here if anyone has the time. In short, I have a page that is dynamic, that sends POST data to a handler, pretty standard stuff. Normally, for me anyway, I know what the field names will be in advance and handle then as usual. In this case the form content is created dynamically from a GUI I created and the names of the fields are suffixed with the product ID. Within the handler I have stripped the POST data down to the main two vars, namely the pid- product ID and qty- quantity ordered and within a loop created a string to explode() like; 9_33_21_66 $oStrArray = explode('_', $ostring); echo "ostring[0] =".$oStrArray[0]; echo "ostring[1] =".$oStrArray[1]; echo "ostring[2] =".$oStrArray[2]; echo "ostring[3] =".$oStrArray[3]; Result => ostring[0] =9 ostring[1] =33 ostring[2] =21 ostring[3] =66 Now, the 1st, 3rd, 5th etc will be the pid and the 2nd, 4th, 6th etc. will be the qty. Only two sets are used in this example, normally 50+ pairs of values will be present. If it helps with the loop that I need to create - if a foreach will not suffice - I can deduce how may pairs will be present and send this as a var via GET from the form setting a value for i, for instance. I need to be able to, within a loop, * pull the first value as a pid * run a subroutine to pull the data from the DB table to get all the product info to display on a confirmation page [this is not ecom - just emailed orders for existing clients] I can do all the MySQL Query stuff it is just rationalising the data extracted from the array Well I am sure you can see from that what I am trying to do, I will need to do the multiplications etc. I do not know how to handle the data in the array created by the explode() In logic I would say this if x in $ostring is even then $ostring is a product id [mysql query to get details from table] next item in array is corresponding quantity - print details of product in a table, do the multiplication to give line total and add to $message ready for email - NEXT pair of vars I really hope that makes sense and someone can point me in the right direction - thanks in advance for any assistance. Regards A |