PHP - What Are Some Modern Ways To Instantiate Classes For Polymorhism?
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 ? Similar Tutorialsclass Database { // actual database interaction // also uses mysql_real_escape etc. } class Users extends Database { function checkIfUsernameExists() { } } class addUser extends Users { // perform all add user stuff } class searchUser extends Users { // all search user stuff } So, to add a new user, I would instantiate, then perform various queries to the addUser class, probably also using the checkIfUsernameExists method in the Users class. Finally, Database would add the record. Question: what do I instantiate? Do I instantiate just the addUser one, or first the Database class? I know how to do it, but what about instantiation, using parent:: self:: etc. etc. (how do I link these clasess together is what I think I mean). I'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. Can a person instantiate a model? If so how do you do it. I already know how to instantiate a class thank you Hi, I'm newbie to php opp. I just need to know if it is possible to instantiate a class like this? $import = new geoIpImportCSV(obtainDownloadFileName(), 'table1'); class geoIpImportCSV { private $input_zip_file; private $db_table; function __construct($input_zip_file, $db_table) { $this->input_zip_file = $input_zip_file; $this->db_table = $db_table; } /* "GeoLiteCity_" . $date . ".zip". */ function obtainDownloadFileName() { return "GeoLiteCity_20101201.zip"; } // ... } It is possible to call a method(obtainDownloadFileName()) like this to the constructor? Best Regards, The junk I've found on phpclasses is well junk and not to mention really old. I started writing my own, but I frankly don't like the plumbing involved. Anyone have a great IMAP class? Something that just does the work for you? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=314342.0 Hello, I found this great free php calandar script here "" by Xu and Alessandro, and I'm trying to modify the code to mark several dates(birthdays YYYY-mm-dd) from a date column in a sql database. I've played around with the _showDay() method but I can't seem to get it working.. I've also tried to create a _showBirthday() method to modify the css as well but with no luck. What I'm trying to do is loop through the database to mark the respective dates on the calendar, and have a href to display a new page with the person's name when I click the specific date. Can anyone help with this. Thanks in advance! 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. 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.
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 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.
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? 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 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 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! 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 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
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! |