PHP - What's Faster Static Functions Calls Or Passing Object Reference
I everyone, I'm developing a small MVC framework for my personal work, now, in order to have access from all the classes to certain variables I've created a registry class, for this to work I have 2 options:
1.- passing every time the registry object to the constructor class(controllers, models, etc) or 2.- create in the registry static set and get so I can reach the variables by Registry::set(name, value) and Registry::get(name) My question is, which one of this two options takes less resources(is faster)? I hope anyone can help me with this, thanks in advance Similar Tutorialshttp://pastebin.com/DbHQSYd7 Been stumbling my way through OOP and seem to be understanding it for the most part (I think..) But I've got a couple questions / kinks that I can't seem to work out. a) How do I return a variable from a class so that a different class has access to it (meta_data) b) I'm getting a "$this" cannot be redefined error (which I know why, but I don't know how to fix)) c) How do I call a function from within one class, where the function resides in another class, AND pass it variables? Any help would be greatly appreciated I've tried to Google warrior A and I think I can figure that one out, but B and C are proving to be the real stumbling blocks. If getValue is given a path which doesn't exist, I can use the isset check to return null. I can also use the uncommitted $tmp =&$tmp[$key];. Why does this prevent an undefined index warning?
public function getValue(string $path) { $path=explode('.', $path); $tmp=$this->config; foreach($path as $key) { //if(!isset($tmp[$key])) return null; //$tmp =$tmp[$key]; $tmp =&$tmp[$key]; } return $tmp; }
Hi all, I'm trying to understand passing by reference. Here is a copy of the code and the results: Code: [Select] <?php $a1 = 15; $b1 = 20; echo addone($a1, $b1); echo "<br/>"; function addone($n1, $n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; }; echo addonetwo($a1, $b1); function addonetwo($n1, $n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; } ?> The result output is: 17 22 17 22 If I change the code to add "&" before the "addone" function: Code: [Select] function addone(&$n1, &$n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; }; Then the output is: 17 22 19 24 I don't understand what's going on. Why is the "&" incrementing the changed variable and in the first example it's incrementing the variables as defined. Ok, starting around line 137 with the functions..... Commented well. Just not sure If im doing it right. Any help greatly appreciated. Basic stuff and still learning. Just trying to figure out if Im passing by reference correctly or if not how to do it. Thanks. php File is attached but heres a snippet. Thanks in advance. Peace, Adam // The grand total and the item total need to be passed BY REFERENCE. function show_table_contents($cart_items, $table, &$grand_total, &$item_total) Was just wondering why some people choose NOT to make use of static functions when initializing objects via Factory Classes/Containers. What are the benefits of initializing the Factory class when for all intensive purposes, it's only used to initialize new classes, etc? Does this have any impact on Dependency Injection? I'm assuming that it doesn't since that would defeat the purpose. --------- Also, I've noticed that there seems to be an intense stigma within the development community in regard to singletons. Are singletons necessarily a bad thing? What about database objects? One argument I've heard is that this can often impact the flexibility of your application in the event that a new instance of said class needs to be initialized(a second completely separate connection). However, I was thinking that you could simply store these objects within a static member variable in the factory class; leaving the Database Class' __construct public in the event that you need to create that second/third/fourth connection. Wouldn't this resolve the issue? Hi all, Why when i set my method to returns by reference its giving me a notice that only variables should return by reference while where is not set to return by reference it don't. Fro example: interface i { function &m(); } class a implements i { public function &m() { return $v; } } $v = new a(); $v->m(); So i just return empty $v. Is this a good practice or should i just ignore the notice Hi, I'm just trying out some basic code and playing around with passing variables by reference and i was reading this on the php manual at this page http://php.net/manual/en/language.references.pass.php : No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid: <?php function foo(&$var) { $var++; } function bar() // Note the missing & { $a = 5; return $a; } foo(bar()); // Produces fatal error since PHP 5.0.5 foo($a = 5); // Expression, not variable foo(5); // Produces fatal error ?> So, i decided to try it out myself like i always do, and i noticed that i'm not getting an error when i do foo(bar()); i.e calling bar() without the & in the function declaration. Infact it works perfectly fine and returns an incremented $a after its passed to foo(). Likewise foo($a = 5); also works great and returns an incremented $a after being passed to foo(). Is this a mistake in the manual or am i missing something? Running PHP 5.3.2-1ubuntu4.5 I'm making a registration form and I'm really new at it. I've had a look about at similar issues but feel like I've got my code set up right, I obviously don't. I have a registration_handler.php and a functions.php file. I'm simply trying to pass an array ($errors[]) from the functions that generate them to a function that prints them out on registration_handler.php. It seems so easy, but I'm not getting it. Here's my code: from functions.php: (this is just an example of one of the functions) // USERNAME (MANDATORY) //uses the clean_names() and checks for empty input function assign_username() { global $conn; $username = $_POST['username']; if(!$username){ $errors[] = "A username is mandatory"; echo "A username is mandatory <br>"; } else { $username = clean_names($username); } //check for duplicate username and return $username if doesn't exist already $username_check = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); $number_rows = mysqli_num_rows($username_check); if($number_rows > 0) { $errors[] = "Username already in use <br>"; echo "Username already in use <br>"; } else { return $username; } return $errors; } // END USERNAME Also from functions.php, the function to print out the error array: //display error array function show_errors($errors) { print_r($errors); } and the function call from registration_handler.php: if(isset($_POST['register_button'])) { //assign clean form variables $firstname = assign_firstname(); $lastname = assign_lastname(); $username = assign_username(); $email = assign_email(); $password = assign_password(); $date = date("Y-m-d"); $errors = array(); show_errors($errors); } I'm intentionally leaving the username out to test this on the form but I only get returned Array() It echos "Username is mandatory" but it seems like it's not passing the error string to the error array Can anyone point me towards what I'm doing wrong, please. I appreciate the replies Edited June 11 by TechnoDiverhi guys im back for more php questions hope you dont get annoyed <?php function getvalue($num) { echo "<input type='text' name='txt1' value='$num'>"; } ?> <html> <head> <title>Home</title> </head> <body> <form action="" method="POST"> <input type="text" name="txt1" id="txt1" value="0"> <input type="button" name="btn1" id="btn1" value="1" onclick="getvalue(1);"> <input type="button" name="btn2" id="btn2" value="2" onclick="getvalue(2);"> </form> </body> </html> here is my code my question is how can i pass the values at the php function? how can i display the passed value to the textbox txt1? is this code correct? echo "<input type='text' name='txt1' value='$num'>"; I have a little problem. I have made a script(function) to connect to the database. this is the script: connect(php) Code: [Select] <?php $server = "localhost"; $username = "username"; $password = "password"; function connectdatabase($type,$database) { if($type == "mysql") { $mysql = mysql_connect($server, $username, $password); mysql_select_db($database, $mysql); } else if($type == "mysqli") { $mysqli = new mysqli($server, $username, $password, $database); } else if($type == "mssql") { $mssql = mssql_connect($server, $username, $password); mssql_select_db($database, $mssql); } function query($query) { if($type == "mysql") { mysql_query($query); } else if($type == "mysqli") { $mysqli->query($query); } else if($type == "mssql") { mssql_query($query); } } } ?> and aanmelden(php) Code: [Select] <?php include("config.php"); connectdatabase("mysql", "[ledensysteem]"); //example if(!empty($_POST)) { if(!preg_match('/^[A-Za-z1-9-]{'.$Minimale_Gebruikersnaam_Karakters.',}$/', $_POST['gebruikersnaam'])) { if(!isset($error)){ $error=1;}else{$error=$error+1;} echo "Je gebruikersnaam moet minimaal {$Minimale_Gebruikersnaam_Karakters} tekens bevaten en mag geen komma of andere onbedoelde tekens zijn<br>Toegestaan is <br>A t/m Z <br>a t/m z <br>1 t/m 9 <br>en -"; } else { echo "geldige gebruikersnaam(goedgekeurd)"; } if(preg_match('/^[A-Za-z1-9-]{'.$Minimale_Wachtwoord_Karakters.',}$/', $_POST['wachtwoord']) && preg_match('/^[A-Za-z1-9-]{'.$Minimale_Wachtwoord_Karakters.',}$/', $_POST['herhaalwachtwoord'])) { if($_POST['wachtwoord'] != $_POST['herhaalwachtwoord']) { if(!isset($error)){ $error=1;}else{$error=$error+1;} echo "niet hetzelfde wachtwoord"; } /*else { echo "hetzelfde wachtwoord (goedgekeurd)"; }*/ } else { if(!isset($error)){ $error=1;}else{$error=$error+1;} echo "wachtwoord moet minimaal {$Minimale_Wachtwoord_Karakters} tekens bevatten!"; } if(!preg_match("/^[A-Za-z1-9_.-]{1,}@[A-Za-z1-9-]{1,}\.[A-Za-z1-9]{2,3}$/", $_POST['email'])) { if(!isset($error)){ $error=1;}else{$error=$error+1;} echo "onjuiste email"; } else { echo "goedgekeurd!"; } if(!isset($error)) // this problem is fixed yesterday on phpfreaks.com forum! { echo "goedgedaan geen errors!"; query("SELECT username FROM phpfreaks WHERE password = private"); // example } } else { ?> <HTML> <HEAD> <TITLE>New Document</TITLE> </HEAD> <BODY> <form method="post"> <input type="text" name="gebruikersnaam" value="gebruikersnaam" maxlength="20" size="20"> <input type="password" name="wachtwoord" value="wachtwoord" maxlength="20" size="20"> <input type="password" name="herhaalwachtwoord" value="herhaalwachtwoord" maxlength="20" size="20"> <input type="text" name="email" value="voorbeeld@domeinnaam.extensie" maxlength="50" size="20"> <input type="submit" name="login" value="inloggen"> </form> </BODY> </HTML> <?php } ?> the problem is, is that i want to pass a variable between functions like $type (the database type) between connectdatabase(); and query(); in the 'aanmelden.php' file is an example of how i use the function (on line 3 and 45 the ones with //example comment) thanks for reading. please help. ps. config.php contains include("connect.php"); i have two functions. In function two it has $id=9. how do i get function one to echo $id? how do i adjust the below example to accomplish this? Code: [Select] $newdb = new Database(); class Database { function one() { $newdb->two(); echo $id; } function two() { $id = 9 return $id; } } hello how do i pass a foreach loop through "Passing by Reference" say i have a foreach loop in a function like this: Code: [Select] function findText(&$output){ $word = Text::find_all(); foreach ($word as $words){ $output = $words->text; } } then one the page i put Code: [Select] findText($output); echo $output; that will just give me the last word in the database. so how do i get it to echo out the array on the page ? thanks function chk_error($site_mode, $obj) { if( $site_mode == 'dev' ) { echo'Error : ('. $obj->errno .') '. $obj->error; } } chk_error($site_mode, $stmt);the above is not working for me. it echos out the text but no values for errno and error. what am i doing wrong? I'm practicing my OOP skills and want to pass $_POST values to an Object's Instance Variables when a form is submitted. This is what I have so far... index.php Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> </head> <body> <!-- Registration Form --> <form method="post" action="results.php"> <!-- Registration Fields --> <div> <label for="email">E-mail:</label> <input type="text" name="email" class="txt" id="email" /> </div> <div> <label for="password">Password:</label> <input type="password" name="password" class="txt" id="password" /> </div> <div> <input type="submit" name="btnSubmit" value="Register" class="btn" id="btnSubmit" /> </div> </form> </body> </html> results.php Code: [Select] <?php include ('classes/FormHandler.class.php'); ?> FormHandler.class.php Code: [Select] <?php class HandleForm { // Define Variables. private $email; private $password; public function __construct($email, $password){ $this->email = $email; $this->password = $password; } } ?> I'm a little stuck on how I initialize the Instance Variables in the Constructor?! TomTees Hi Guys, I'm new to OOP. I've mastered some basic syntax, but am wondering about an issue of design. To clarify in this example, I'm simply looking to pull Team data from a Database (I've not included my db class (PDO wrapper) although I know it is working. Although I have seen this sort of method below in a book (I believe and on the net) and it does work, I cannot help thinking coupling the DB class so tightly with the Team Class isn't a great approach. Can anyone give me feedback as to whether my approach is valid? While I can see the negative issue of tight coupling (i.e. changes to any database method would require multiple changes in Team (as team methods were added), I cannot really see an alternative way of doing this? I guess this is an issue of a design pattern or more advance OOP. Can anyone suggest an alternative way and/or more reading on making the coupling looser while still achieving my objectives? Should, for example, all DB functionality in getName be done during implementation? I initally thought pushing all db related functionality inside a Team method was wise and the best way then to add further methods, i.e. getResults method would be similar to getName but obviously with a different query and processing afterwards inside Team, but now I wonder if all should be in the implementation, or is there another approach? Thanks in advance. // create team class class Team { private $db; private $team_name; private $team_id; private $result; // in constructor lets pass DB object public function __construct($db) { $this->db = $db; } //function to get team name public function getName($team_id) { $this->team_id = $team_id; $this->db->query("SELECT team_name, nickname, founded FROM club WHERE team_id=:teamid"); $this->db->bind(':teamid', $this->team_id); if ($result = $this->db->single()); { return $result[]; } } }// end class // Implementation $team_id=1; //passed from user input // First Create Db Object with correct passed variables $database = new Database($server,$db_type); // Invoke DB connect method $database->connect(); // Now create Team object, pass it database object $team = new Team($database); // call Team method $team_display = $team->getName($team_id); // close db $database->closedb(); I don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error.
here's the code for the mysqli object that i want to pass to another class
class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... }and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here }and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqliand some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqliis there something wrong with the logic that I've made? please help 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? I work with a large codebase and I have this situation come up fairly often:
the legacy class has large objects such as:
$design->motor->dimensions->a; $design->motor->dimensions->bd; $design->specifications->weight; $design->data->height; //etcWhen I create a new class, that class sometimes operates on the specific data, so say: class MyClass { public function compute($weight, $height, $a) { //stuff } } //and I call this for example as such: (new MyClass())->compute($design->specifications->weight, $design->data->height, $design->motor->dimensions->a);CONS: Potential issue: if design specs change and I need to change things parameters in "compute" function, I need to "re-key" the variables I pass to the function, and adjust things accordinly in MyClass as wel. PROS: only the exact data is being passed, and this data can come from anywhere it is viable, so in effect the function is fairly well separated, I think. Alternative option for me is to pass the entire design object, i.e class MyClass { public function compute(&$design) //can also be done via DI through a setter or constructor. { print $design->specifications->weight; print ($design->data->height + $design->motor->dimensions->a); //stuff } } (new MyClass())->compute($design);PROS: In this case when things change internally in which variables are needed and how things are computed, I only need to change the code in compute function of the class itself. CONS: MyClass now needs to be aware of how $design object is constructed. When it comes to this parameter passing, and Dependency Injection like this in general, does Computer Science advocate a preference on this issue? Do I pass the entire object, or do I pass only the bits and pieces I need? my code: Code: [Select] echo $Profile['display']; ECHO's out: 0|1|0|1 Now I want to explode these, which is easy Code: [Select] $display = explode("|", $Profile['display']); But Now I want to use a php function to check if any of the array's = "1" and have the value set to $value= "checked"; I could do this by doing Code: [Select] if ($display['0'] == "1"){ $value = "checked"; } and then 1 2 3 and so on.. but I want a faster way, maybe a for loop, or a simpliar easier way to just check if each array = 1, make $value = checked Possible right? Hi all I wonder if you could give me some advice. I basically have a mysql database of staff who work at a college, I have a front which displays details of a staff member, I grab the details using userdetails.php?id=44 (44 being the ID of the staff member) One field I have in my MySQL database is "title", which is basically Mr Ms Mrs Miss Dr At the moment, I store the "title" value in the database as "CHAR", so it appears as "Mrs" for example when I print print $row['title']; What I want to know is, which is the best method of storing and getting this data. Is it best to ----------------------------------------------------- 1: Continue as I am and keep text values in the database stored as CHAR[/li][/list] ----------------------------------------------------- 2: Change it so that instead of storing "Mr", "Dr" as CHAR, I would store them as numeric values, so; 2 would be Mr 3 would be Mrs 4 would be Dr then do a if($row['title'] == 2) { print "Mr"; } elseif($row['title'] == 3) { print "Mrs"; } elseif($row['title'] == 4) { print "Dr"; } ----------------------------------------------------- 3: Change it so that instead of storing "Mr", "Dr" as CHAR, I would store them as numeric values, but then have another database table which holds what value each number is, so my new database table would be like --- title_values ---- id value 2 Mr 3 Mrs 4 Dr ------------------------- then on the front end, do a SELECT such as SELECT `value` FROM `title_values` WHERE `id` = "'.$row['id'].'" I guess the advantage to this one, is that I can modify the list of titles and expand it. ----------------------------------------------------- which of those is generally considered better? faster? and less server intensive? or is there a better way to do it? Thanks very much |