PHP - Ways Of Setting Vars In __construct()
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 Similar TutorialsI am trying to familiarize myself with using classes and I have a question regarding the use of __construct and __destruct. When using both, should the functions be public or private? Hi, I'm fairly new to OOP so please bare with me. I've been given to understand __construct is put forth in order to do that as soon as the object is created. Now I've created an object to control sessions. so here is my construct code includes a function within that object and session_start(). However, I get the error that the function within that object is non-existent but the function is right underneath the __construct function. should I put __construct last thing in my object? ANy help on this issue would be excellent! Thank you. This line of PHP mysqli::__construct($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname); returns Quote Fatal error: Non-static method mysqli::mysqli() cannot be called statically in Why does it do this? I want to use the OOP MySQLi methods in PHP and NO procedural PHP
Hi! I'm new here private PDO $connection; function __construct(PDO $connection) { $this->connection = $connection; connect.php class dbh{ private $host = "localhost"; private $user = "root"; private $pwd = ""; private $dbname = "cms"; protected function connect() { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname; $pdo = new PDO ($dsn, $this->user, $this->pwd); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; } }
function.php // not a whole code class CategoriesData extends dbh{ public function getAllCategories() { $sql = "SELECT * FROM categories_tbl"; $stmt = $this->connect()->query($sql); while ($row = $stmt->fetch()){ echo $row['category_name'] . '<br>'; } } public function getCategoryName() { $sql = "SELECT category_name FROM categories_tbl"; $stmt = $this->connect()->prepare($sql); $stmt->execute(); $category = $stmt->fetch(PDO::FETCH_OBJ); if($category == null) { return null; }else { return $category->category_name; } } public function getCategoryDetials() { $sql = "SELECT * FROM categories_tbl"; $stmt = $this->connect()->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll((PDO::FETCH_OBJ)); return $result; } public function addCategory ($filter_name, $filter_title, $filter_description, $filter_slug) { $sql = "INSERT INTO categories_tbl (category_name, category_title, category_description, category_slug) VALUES (?, ?, ?, ?)"; $stmt = $this->connect()->prepare($sql); $stmt->execute([$filter_name, $filter_title, $filter_description, $filter_slug]); } public function deleteCategory($delete_category_id) { $sql = "DELETE FROM categories_tbl WHERE category_id = ?"; $stmt = $this->connect()->prepare($sql); $stmt->execute([$delete_category_id]); } } }
Hello, I'm in need of help. Sometimes my PHP reads XML from a ssh and it tends to fail at times. Heres my complete error: Code: [Select] [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: Entity: line 3: parser error : Premature end of data in tag info line 2 in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: ^ in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/nmdgamin/public_html/private/includes/functions/revision.php:69 Stack trace: #0 /home/nmdgamin/public_html/private/includes/functions/revision.php(69): SimpleXMLElement->__construct('<?xml version="...') #1 /home/nmdgamin/public_html/private/includes/functions/update.php(16): CheckRemoteRevision('SpaceBuild') #2 /home/nmdgamin/public_html/prv_updater.php(13): Update() #3 {main} thrown in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 Remote function: function CheckRemoteRevision($Name){ if($Name){ if($Query = MySQLQuery('SELECT name, url, sv_revision FROM data WHERE name=\''. $Name .'\';')){ if($XMLFile = shell_exec('svn info \''. $Query['url'] .'\' --username anonsvn --password anonsvn --xml')){ if($DCheck = explode(' ', $XMLFile)){ if($DCheck[0] == 'svn:'){ $Revision = '0'; $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); return False; } } $XML = new SimpleXMLElement($XMLFile); foreach($XML->entry as $Attribute){ $Revision = $Attribute['revision']; } if($Query['sv_revision'] < $Revision || $Query["sv_revision"] != $Revision){ $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); } return $Revision; }else{ return False; } }else{ return False; } }else{ return False; } } How would I full proof this from getting this error again, It seems to happen at completely random times. I'm not very good with XML in PHP Thanks! Hi, I'm having a bit of a problem understanding why I'm not able to use the class I'm extending off of functions. I have a category class that extends off my core class, inside that category class, I'm able to use the core functions and variables inside all custom functions, but not the __construct function. So, to be clear, inside class class, I'm able to call $this->core->function() inside custom functions, such as function add_parent(), but not the __construct function. Why is this happening, what is the logic behind this? This is how I'm extending the class off of the core class: Code: [Select] <?php $core = new core; $parent = new parents; $parent->core =& $core; ?> With this, like I said, I'm able to use all of my core functions inside all other classes called this way, so inside all of the other classes I can do: Code: [Select] <?php $this->core->function(); ?>everywhere besides __construct(). Do I not have the class called properly? Do I need to pass my core class through differently? How can I fix this? Thanks. Hey there, This has me stumped here. I'm supplying an array as a valid argument to the class like so: $mysql_configuration = array( 'MySQL_Host' => "localhost", 'MySQL_Username' => "fdsfdsfsdfsd", 'MySQL_Password' => "sdf-sdf543", 'MySQL_Database' => "sfsdfsdfsdf"); $radio_core = array('Main' => new Radio_Core($mysql_configuration), 'Requests' => new Radio_Requests, 'Accounts' => new Radio_Accounts, 'Content' => new Radio_Content); And here is my small class: class Radio_Core { public $mysql_handle; function __construct($mysql_array) { $this->mysql_handle = mysql_connect($mysql_array['MySQL_Host'], $mysql_array['MySQL_Username'], $mysql_array['MySQL_Password']); if(!$this->mysql_handle) { die("The station failed to connect to the MySQL database."); } else { mysql_select_db($mysql_array['MySQL_Database'], $this->mysql_handle); } return 1; } } And when it is called I am prompted with the error that the argument is missing for it? Quote Warning: Missing argument 1 for Radio_Co :__construct(), called in /home/atomnetw/public_html/Chris-Martino.com/projects/radio/index.php on line 10 and defined in /home/atomnetw/public_html/Chris-Martino.com/projects/radio/Core/radio.class.php on line 15 Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'atomnetw'@'localhost' (using password: NO) in /home/atomnetw/public_html/Chris-Martino.com/projects/radio/Core/radio.class.php on line 17 Thanks for your time! Can I not pass references into class properities from outside the object? class db_manipulation { private $connection = NULL; function __construct(&$database_connection) { $this->connection = $database_connection; if (!$this->connection) die('couldnt connection to database'); } function __destruct() { mysqli_close($this->connection); } } Results in: Warning: mysqli_close() [function.mysqli-close]: Couldn't fetch mysqli in Hello,
I've noticed that there are services that I can pay to have my code
checked for possibly unsafe / insecure code.
But I'd rather audit the code myself, as my code is not meant to make money.
Is there a list of safe ways to use PHP?
Also is there any automatic way to do this that is free?
For instance is there a code checker?
I've noticed there are a number of ways to do PHP wrongly
that can be easy to overlook. Is there a list of common PHP pitfalls?
Thanks.
Is there a shorter way to achieve this in a single foreach()? foreach ($_SESSION['cart']['content']['sizes'] as $content); foreach ($_SESSION['cart']['content']['sizem'] as $content); foreach ($_SESSION['cart']['content']['sizel'] as $content); I am thinking something like: foreach ($_SESSION['cart']['content']['sizes'] && $_SESSION['cart']['content']['sizem'] && $_SESSION['cart']['content']['sizel'] as $content); or foreach ($_SESSION['cart']['content'] = ['sizes'] || ['sizem'] || ['sizel'] as $content); I would realy like to study php, other than taking other codes and editing them i havnt got a clue. What would be the simplest way? Do you use a method in the child class? Personally I use Code: [Select] parent::$this->whatever; But I was wondering what you guys do. Hello, mates! I am new to PHP. I want to store some data shared between requests. I know that it is possible with memcached and shared memory in Unix. What ways to do it could you advice? How could I realize background service in PHP? Thank you.
Is this an acceptable way to instantiate classes?
//$_SESSION['product'] = {'ProductA', 'ProductB', ... 'ProductX'} $p = new $_SESSION['product'](); $p->save();I am usually used to calling out classes explicitly where class name is not a variable but a hardcoded string. Sometimes I use if/then/else in order to do this. Here it is a variable and it bothers me a little bit. But PHP allows me to do this. Is this an acceptable latest & gratest modern PHP object oriented web technology technique or not ? 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>"; 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> } } ?> 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)); } } } } 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. 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?> |