PHP - How To Declare Array Variable As Public Inside A Class?
I tried these below,
Code: [Select] class Site extends Controller { function Site() { public $data = Array(); } } but it fail? Thanks in advanced. Similar TutorialsI keep running into a bunch of error when I declare the page variable in my model. What syntax do I need to use throughout the class? Code: [Select] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Header_Model extends CI_Model{ var $page = substr(end(explode(DIRECTORY_SEPARATOR, $_SERVER['PHP_SELF'])), 0, -4); function get_page_name() { $this->load->library('common'); $page_names = $this->common->page_names(); $title = (array_key_exists($page, $page_names) !== false) ? $page_names[$page]: ''; if (array_key_exists($page, $page_names) !== false) { $title .= " | Jason Biondo"; } return $title; } function get_js_page_file() { if (file_exists("./assets/js/pages/${page}.js")) { $javascript = "<script type=\"text/javascript\" src=\"./js/pages/${page}.js\"></script>"; } return $javascript; } } Hi, Im wondering if there is an easy way to get items out of an array returned by a function inside a class. A code example would be: Code: [Select] class modDB { public function getPwdSalt() { $arr = array("salt", "password"); return $arr; } } ?> And what i would like to be able to do is something like: Code: [Select] $modDB = new modDB; echo $modDB->getPwdSalt()->[1]; and just get returned 'password'. Is something like that possible? Many Thanks. I'm started learn PHP about 7 days.I want to know>>is this possible to declare a Variable like $password="Phpfreaks"??? Can you set a variable like so: Function something(bob = true) { } Howdy colleagues,
I have noticed some programmers re-declare their variables before using them. Like so:
$name = ''; $name = 'Elizabeth';First of all, why do they do that? Variables are being re-written with each "=" anyways. Secondly, do you believe this is better than just doing: $name = 'Elizabeth';Thank you Hi, I have these variables for pages I navigate to because I pass them in the query string. However, I need a variable for the homepage (index.php), before any query string is created. I cant declare a vari $_GET['intro'] ; $_GET['about'] ; $_GET['contact'] ; However, I need a variable for the homepage (index.php), before any query string is created. I cant declare a variable in index.php because it will be used throughout the entire website. I also cant declare the variable in home.php (the bulk content of the homepage) because I need to use the variable before home.php is included. Is their a trick for this? Thanks! I am echoing a variable that is an array. I want to change the first part of the variable but don't know how to manipulte names inside the ['brackets'] Code: [Select] echo $row['v1_name']);?> lets say I have a value called $var = v1. How do I substitute that like this: Code: [Select] echo $row[$var.'_name']);?> I know the above doesnt work, but thats what i want it to do :-) Hi, The array shown below is causing problems. I know this for sure because when I comment the array out the script runs. Is it: 'pswrd1'=>SHA1('$_POST['pswrd1']') inside the array causing the script not to run?? All help will be greatly appreciated. $register_data = array('username'=>$_POST['username'], 'first_name'=>$_POST['first_name'], 'last_name'=>$_POST['last_name'], 'address'=>$_POST['address'], 'postcode'=>$_POST['postcode'], 'country'=>$_POST['country'], 'e_mail'=>$_POST['e_mail'], 'pswrd1'=>SHA1('$_POST['pswrd1']'), 'phone_no'=>$_POST['phone_no']); I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? This probably doesn't matter much, but I am using a 'Display' class for final output to the browser. The class will display the obvious HTML header and then display either the full site or the mobile site. It also displays the CSS / JS (which is previously selected in the page-specific controller code as there are variations based on server-side checks). Basically it is the ONLY class that actually needs to send anything to the browser. When I begin output and echo inside the class, that is the end of the script - there is no more server-side code to execute. If I shouldn;t echo inside the class, is it that bad to do so? Well in the class UserValidator I have a public method validate(), which checks the validation type and then calls specific private methods to execute the validation script. It gets a bit tricky here since the method validate() has to decide what private method to call. I am thinking about using call_user_func_array(), the script currently looks like this below: Code: [Select] public function validate(){ // The core method validate, it sends requests to different private methods based on the type if(empty($this->type)) throw new Exception('The validation type is empty, something must be seriously wrong...'); if(is_array($this->type) and !is_array($this->value)) throw new Exception('Cannot have scalar value if the type is an array.'); if(!is_array($this->type) and is_array($this->value)) throw new Exception('Cannot have scalar type if the value is an array.'); // Now we are validating our user data or input! $validarray = array("register", "login", "password", "session", "email", "reset", "profile", "contacts", "friends"); foreach($this->type as $val){ $method = "{$val}validate"; if(in_array($val, $validarray)) call_user_func_array(array($this, $method), array()); } } The method to execute depends on the validation type passed into the validator class, so it is somewhat like a dynamic function call. The problem is, well, I am not sure if I am using call_user_func_array() properly. I read it from php manual that it needs to accept a class instance, but there is no such instance inside a class method so I use $this in the argument. Is this the correct way of using call_user_func_array()? If not, how am I supposed to do this? 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. I've searched all over for the past few days trying to figure out what I'm doing wrong. Basically what I'm trying to do is create a prepared statement inside my User class. I can connect to the database, but my query does not execute as expected. Here's the code for my User class Code: [Select] <?php include '../includes/Constants.php'; ?> <?php /** * Description of User * * @author Eric Evas */ class User { var $id, $fname, $lname, $email, $username, $password, $conf_pass; protected static $db_conn; //declare variables public function __construct() { $host = DB_HOST; $user = DB_USER; $pass = DB_PASS; $db = DB_NAME; //Connect to database $this->db_conn = new mysqli($host, $user, $pass, $db); //Check database connection if ($this->db_conn->connect_error) { echo 'Connection Fail: ' . mysqli_connect_error(); } else { echo 'Connected'; } } function regUser($fname, $lname, $email, $username, $password, $conf_pass) { if ($stmt = $this->db_conn->prepare("INSERT INTO USERS (user_fname,user_lname, user_email,username,user_pass) VALUES (?,?,?,?,?)")) { $stmt->bind_param('sssss', $this->fname, $this->lname, $this->email, $this->username, $this->password); $stmt->execute(); $stmt->store_result(); $stmt->close(); } } } ?> And here's the file that I created to instantiate an instance of the user class. Code: [Select] <?php include_once 'User.php'; ?> <?php //Creating new User Object $newUser = new User(); $newUser->fname = $_POST['fname']; $newUser->lname = $_POST['lname']; $newUser->email = $_POST['email']; $newUser->username = $_POST['username']; $newUser->password = $_POST['password']; $newUser->conf_pass = $_POST['conf_pass']; $newUser->regUser($newUser->fname, $newUser->lname, $newUser->email, $newUser->username, $newUser->password, $newUser->conf_pass); ?> And lastly heres the form that I want to get info from the user to insert into the database Code: [Select] <html> <head> <title></title> <link href="stylesheets/styles.css" rel="stylesheet" type="text/css"/> </head> <body> <form action = "Resources/testClass.php" method="post" enctype="multipart/form-data"> <label>First Name: </label> <input type="text" name="fname" id="fname" size="25" maxlength="25"/> <label>Last Name: </label> <input type="text" name="lname" id="lname" size="25" maxlength="25"/> <label>Email: </label> <input type="text" name="email" id="email" size="25" maxlength="40"/> <label>Username: </label> <input type="text" name="username" id="username" size="25" maxlength="32"/> <label>Password: </label> <input type="password" name="password" id="password" size="25" maxlength="32"/> <label>Re-enter Password: </label> <input type="password" name="conf_pass" id="conf_pass" size="25" maxlength="32"/> <br /><br /> <input type="submit" name="submit" id="submit" value="Register"/> <input type="reset" name="reset" id="reset" value="Reset"/> </form> </body> </html> Hi guys, I am trying something fairly simple but I'm not sure if this would be a good practice. Basically I am using a big class called CommonLibrary that holds common functions as methods and common variables as static variables. But I have some variables here and there like $allAlphabet = range ('a' , 'z'), that cannot be declared as a property because it gives me a parse error. I don't want to call an object for this class because instancing it is of no use. Values will never change with regards to instances. So the next best thing that I tried was declaring all static variables first, and then changing thei property values inside the class __construct with self::$variable = 'somevalue', and then using this code below to assign values to the empty static variables. $dummyObject = new CommonLibrary; unset($dummyObject); echo CommonLibrary::$staticVariable; // This property is NULL before the constructer is triggered. Anyone recommend any better ways of doing this? Thanks in advance! How can I call a public function inside of another public function? The get_primary_edge() says it's undefined, but it's just another public function in the class so shouldn't this work? Code: [Select] public function get_dynamic_edge($uid) { $uid = (int)$uid; $sql = "( SELECT `users`.`id` FROM partners INNER JOIN `users` ON `partners`.`user_id` = `users`.`id` WHERE partners.friend_id = '${uid}' AND `approved` = 1 ) UNION ALL ( SELECT `users`.`id` FROM `partners` INNER JOIN `users` ON `partners`.`friend_id` = `users`.`id` WHERE `partners`.`user_id` = '${uid}' AND `approved` = 1 )"; $result = mysql_query($sql) or die(mysql_error()); $i = 0; while (($row = mysql_fetch_assoc($result)) !== false) { $dynamic[$i] = array( 'uid' => $row['id'], 'score' => get_primary_edge($row['id']), ); $i++; } print_array($dynamic); } I 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? 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? |