PHP - Help With Classes
Similar TutorialsI've been spending long hours learning about classes and their magic methods. I just came across a tutorial which showed a constructor like this:
class Device { //... public function __construct(Battery $battery, $name) { // $battery can only be a valid Battery object $this->battery = $battery; $this->name = $name; // connect to the network $this->connect(); } //... }the Battery part instantly caught my attention. Here had previously made a Battery class (and a more complete Device class) but the next thing he did really caught my interest: $device = new Device(new Battery(), 'iMagic'); // iMagic connected echo $device->name; // iMagicwhat the hell is going on here? Is this another way to include the methods and properties of one class into another class, in order words is this the same thing as: class Device extends BatteryI don't think so because this new Battery() thing looks more like its creating an object inside the Device object. Previously the only way I could to that was to type $battery = new Battery() inside one of my methods. But this looks like hes doing something different. Can anyone explain whats going on here? The whole tutorial is he http://code.tutsplus...-php--net-13085 in the main Device method he has a premade $battery variable to hold the Battery object. Sometimes I have multiple classes containing functions which I'd like to include in my main class. I can only extend one class, so I usually extent a class containing only properties, no methods. I still don't know what difference making that info class abstract is, I'd appreciate if anyone could tell me. Also I'd love to know what the point in static methods is. I've never used them because I've never seen the point. Is it just to make it easier to call the methods because you don't need to create an object instance to call them? Sorry for the extra questions, the first one is what I'm really wondering about. Not sure how to describe what I'm trying to do here in the title, but here goes with what I am trying to accomplish. I've got a few hundred lines of code in total so far, so I'll try to keep it as short as I can. I've got an application that I am programming using classes for each module and right now I am coding the base classes that I need in order for it to run (database, errors, logging, etc). What I'm doing for my database class is I have a query factory and it extends the MySQLi class so I can process, clean and code the rest of my app faster. I also have another, unrelated class "Error", which will be used for processing errors I might come across. I'd rather do it this way instead of having to call trigger_error and error_log every time there is an error. I'd also not like to have to call a new instance of an object every time I need to use something from that class. Is there any way I can call a class within a class and return it as an object for all the methods within the class? I've tried the methods below, but no luck I've tried others, but I'm trying to keep it brief and get what I'm trying to do across. <?php class QueryFactory extends MySQLi { public $err = new error(); //Doesn't work. public $err = error(); //Nope. #This is the function that I need the $err object for. function set($fields, $newvals) { if ( is_array($fields) && is_array($newvals) ) { if ( count($fields) != count($newvals) ) { //Instead of below, I want to do something like $err->('Array lengths must match for method', 256, $islogged = 1); trigger_error('Array lengths must match for method', 256); } } } } The thing is, I have a "run.inc.php" which does include and create new objects for running just the basic app and if I try to redeclare the error class in query.class.php, it gives me an error saying I can't do that, but if i try to call $err from the page that has all the classes defined it throws an error saying that my method is undeclared. I'd like my error class be available to every other class I create so I can display and log errors as needed. Any suggestions or links to point me where I'd like to go? I have just start using PHP classes and was wondering how you continue an instance of a class in another file. For example I have a folder called "includes" where I includes files that I send data to when I perform ajax request. However how do I continue an instance of class in these files? Hope that makes sense. Thanks for any help. ini_set('display_errors', 1); error_reporting(E_ALL); class A { private function operation1() //only be used inside this class { echo 'operation1 called'; } protected function operation2() //only inside this class { echo 'operation2 called'; } public function operation3() //public can be used in any class { echo 'operation3 called'; } } class B extends A { function _construct() { //$this->operation1(); //$this ->operation2(); $this->operation3(); } } $b = new B; can someone please tell me why this code doesn't work ? Hi. I want to know how I access calsses in PHP. I mean how I search for class that I want and need. do I need to search in php.net? and what editors that provide access the the whole php classes and who they keep updated? Cheers. im currently doing a large php project and i am confident i can do it. Its a basic forum like phpbb or mybb where users can download the files and instal. however i have looked through their code and i see they use classes. I have never learned to do classes since i havent had to use them yet. should i be using them now for this project? do i need to? and if so then what are the benefits? How can i get my class to be showed on the front page here is the front page <?php require('ex2.php'); $start = new A(); $tart->Display(); ?> now here is ex2.php <?php ini_set('display_errors', 1); error_reporting(E_ALL); class A { public $title = "test1"; public $end = "test2"; } function __set($name, $value) { $this->$name = $value; } function Display() { echo $title; echo $end; } ?> shoudn't this print test1 and test2 ? Take the following example: <?php class a { var $things; public function __construct($stuff) { $this->things = $stuff; } } class b { var $morethings; $this->morethings = "something"; } $c = new a(new b); echo $c->things->__PARENT__; ?> The line "echo $c->things->__PARENT__;" (as you can probably imagine) does not work. How would I output what the 'b' object is stored in ('a')? Hello, maybe back to basics, but [PHP] pobierz, plaintext Hi, I want to build a simple calculator class and one of the function is to calculate the factorial, but for some reason I cannot get this to work. Here is class: ========= Code: [Select] <?php class Calculator { function factorial($n) { if($n==1) return 1; else return factorial($n-1)*$n; } }//END CLASS Calculator $calculator=new Calculator(); print $calculator->factorial(3); ?> But it doesn't work, I know this is simple but I am a little rusty with object oriented programming. I'd appreciated any help! Hello All, I am fairly new to PHP class development, and I was wondering if it is normal behaviour to see classes not being able to access global variables related to PHP-based requests ($_GET, $_SESSION, etc.)? I seem to either have to use "global <var>" inside of the class to access the data, or I am forced to change the methods so then such required data is passed in as parameters. Perhaps I am just doing something wrong? Here is an example of what I mean: class Something { function aFunc() { if (isset($_SESSION['somedata'])) { return false; } // this always returns false whether I had set the value or not } function bFunc() { global $_SESSION; // figured this would already be in a global accessible scope if (isset($_SESSION['somedata'])) { return false; } // now this will return false only when the value is set } } Now the above example is commented to demonstrate what I was meaning above, and I was wondering if this was the 'norm' when developing classes for PHP (and thus such values should be passed as parameters)? Thanks! Hi there,
This might a newbie question but I need help understanding PHP classes which am currently learning.
I have an index page.
With this three included files.
database.php
config.php
account.php
on database.php, the class is declared using $connection new Database(...), on this page is also all the coding for this class.
In config.php is a declared class of $account new Account($user_id);
and on account.php is all the details for the account class.
on the index.php is echo $account->sayHello;
However, My page is throwing out an error because I'm trying to use $connection->query(..) in my account.php / Account class.
I have tried to extend the Account class with Database but still have no luck.
How can I make sure the I can use a class function from another page in my Account class?
Thanks for reading
If I have defined an instance of a class in one script how do I then use this same instance and the same variable in other scripts? For example say I have this code in a file called "index.php" include("myclass.class.php"); $myclass = new myClass; $myclass->$variable = "hello world"; However if I then have this code in a file called "page1.php" when I try to access the same variable it is empty. include("myclass.class.php"); echo($myclass->$variable) How can I use the same instance of this class across all files keep the variable values the same? Thanks for any help. I'm looking for suggestions / recommendations for php classes that interact with Skype. It's a bit difficult to fully describe what I want to do, but think in terms of a internal customer support application leverages the functionality of Skype. We will need to do things like open Skype progamatically, monitor the elapse time and acquire that data for statistical analysis, things like that... I know Skype has an API, so I'm thinking someone has probably already written some classes that work with it... Naturally, I'm trying to avoid "reinventing the wheel". Anyone know about this sort of thing? OK, im not too crash hot on classes, so hoping someone can help me with this error: Quote Fatal error: Call to a member function add_current_page() on a non-object in /path/to/includes/application_top.php on line 312 This is from an osCommerce application (I know someone will probably tell me to post in 3rd party scripts, but I am more interested in whats generally causing the error). The thing that confuses me is that application_top.php is only 236 lines long. So I am trying to run my execute function from my database class from my email class. I have SMTP system to handle emails on the website. I am working on a function in the email class called addAccount. It is suppose to add a row in the database under the SMTP table. When I run the function, I get no parsing errors, so I add the or die to my query from the execute function, still nothing at all. So here is some code: -The addAccount function from Email.php: function addAccount($name, $email, $username, $password, $protocol, $port, $server){ //Error checking & cleaning vars. will be done in the application, not the backend. if(!empty($name) && !empty($email) && !empty($username) && !empty($password) && !empty($proctocol) && !empty($port) && !empty($server)){ $name = ucwords(strtolower($name)); $email = strtolower($email); $this->db->execute("INSERT INTO ".TBL_SMTP." (name, email, username, password, protocol, port, server) VALUES ('$name', $email', '$username', '$password' '$protocol', '$port', '$server')", true); return true; }else return false; } -The entire email class from Email.php <?php require_once("pear/Mail.php"); class Email{ var $from_name, $from_email, $to_name, $to_email, $subject, $body, $host, $port, $username, $password; private $db = NULL; function __construct(Database $db){ $this->db = $db; } function dbEmail($id, $name, $email, $subject, $body){ $q = $this->db->select(TBL_SMTP, "*", "id='".$id."'"); if($q->numRows() > 0){ $f = $q->fetchRow(); $this->from_name = $f['name']; $this->from_email = $f['email']; $this->username = $f['username']; $this->password = $f['password']; $this->host = $f['protocol']."://".$f['server']; $this->port = $f['port']; $this->to_name = $name; $this->to_email = $email; $this->subject = $subject; $this->body = $body; return sendEmail(); }else return false; } function sendEmail(){ $from = $this->from_name." <".$this->from_email.">"; $to = $this->to_name." <".$this->to_email.">"; $headers = array ('From' => $this->from, 'To' => $this->to, 'Subject' => $this->subject); $smtp = Mail::factory('smtp', array ( 'host' => $this->host, 'port' => $this->port, 'auth' => true, 'username' => $this->username, 'password' => $this->password)); $mail = $smtp->send($to, $headers, $this->body); if(PEAR::isError($mail)){ //echo($mail->getMessage()); //For debugging purposes only return false; }else return true; } function addAccount($name, $email, $username, $password, $protocol, $port, $server){ //Error checking & cleaning vars. will be done in the application, not the backend. if(!empty($name) && !empty($email) && !empty($username) && !empty($password) && !empty($proctocol) && !empty($port) && !empty($server)){ $name = ucwords(strtolower($name)); $email = strtolower($email); $this->db->execute("INSERT INTO ".TBL_SMTP." (name, email, username, password, protocol, port, server) VALUES ('$name', $email', '$username', '$password' '$protocol', '$port', '$server')", true); return true; }else return false; } } $email = new Email($db); ?> The entire database class from Database.php <?php class Database{ var $mysqli, $result, $q, $affectedRows; function __construct($host, $user, $pass, $db){ $this->mysqli = new MySQLi($host, $user, $pass, $db); } function execute($query, $error = false, $mode = MYSQLI_STORE_RESULT){ $this->q = $query; if(!$error) $result = $this->mysqli->query($query, $mode); else $result = $this->mysqli->query($query, $mode) or die($this->mysqli->error); if(is_object($result) && $result instanceof MySQLi_Result){//if result is a object and is part of the mysqli class? $this->result = $result; $this->affectedRows = $this->result->num_rows; }else $this->affectedRows = $this->mysqli->affected_rows; return $this; } function fetchRow($mode = MYSQLI_ASSOC){ return $this->result->fetch_assoc($mode); } function fetchAll($mode = MYSQLI_ASSOC){ $row = $this->result->fetch_all($mode); return !empty($row) ? $row : array();//if not empty return row, else return an array? } function numRows(){ return $this->affectedRows; } function delete($table, $where){ return $this->execute("DELETE FROM ".$table." WHERE ".$where); } function deleteAll($table){ return $this->execute("TRUNCATE ".$table); } function update($table, $set, $where){ return $this->execute("UPDATE ".$table." SET ".$set." WHERE ".$where); } function select($table, $select = "*", $where = NULL){ if(is_null($where)) $where = ""; return $this->execute("SELECT ".$select." FROM ".$table." ".$where); } } $db = new Database(DB_HOST, DB_USER, DB_PASS, DB_DB); ?> Chances are it is my email class since it was 100% written by me. The database class I had some help from a member here. What do you experts think? I am working with the Zend Framework and I noticed that some of the classes do not have constructor. For instance, Zend_ACL does not have a constructor. What happens with this class is instantiated? Is it just a sort of empty object? The class does not extend another class so a parent constructor is not being called. hello, all i am trying to learn php, and currently trying to get my head around using classes. i have the following layout: index.php Code: [Select] <?php include("config/autoloader.php"); $content = new content(); $content->get_content(); // loads Content! $content->edit_content(); // Edits Content! ?> <?php $navbars = new navbars(); $navbars->get_navbar1(); // loads navbar1! ?> config/autoloader.php Code: [Select] <?php function spl_register_autoload($content) { include_once("classes/" . $content . ".php"); } function spl_register_autoload($navbars) { include_once("classes/" . $navbars . ".php"); } ?> content.php (content class file) Code: [Select] <?php class content { public function get_content() { echo "Show me the content!"; } public function edit_content() { echo "Edit the content"; } } ?> navbars.php navbars class file Code: [Select] <?php class navbars { public function get_navbar1() { echo "Show me the navbar1!"; } } ?> i keep getting the 500 - internal error on iis, but works on a single class file, as soon as i add more then one i get the error, can someone please help me and explain where i have gone wrong. thanks, all. Hi, I am running a web server for which I place the php files in /var/www folder and they work fine from the browser. Now, I wish to use SSH2 class that can be found at (http://phpseclib.sourceforge.net/documentation/net.html#net_ssh_ssh2). I have placed SSH2.php in the same folder (/var/www) but it doesn't work. I have also copied the file in /usr/share/php (which is the path returned by ini_get('include_path') command). Where do I put my required file (SSH2.php) so that I can use it. Thanks Yo, everyone. I got a problem with the class i wrote for my coding, I need to use the class for every data that will show up. for that i used a 'for' cycle, but it seems i get only the first one of the cycle right. well the problem seems that the class can only be included once and for the rest, I got a header problem. Is there a way to actually use classes in a cycle? Thanks in Advance. |