PHP - Object Inheritance (get Instance)
Hello,
I'm attempting to build a Model View Controller and I've run into some issues with inheriting objects / extending classes. The application is focused around a "SuperObject", which contain instantiated libraries, helpers, controllers, models and views. I current have a Base class, which is effectively the "SuperObject". Previously I called the function GetInstance() within my model to get an instance of the SuperObject and assign it to a variable. So, $this->Instance->(The Object)->(The Method)(); However, I want to remove the need for that variable $this->Instance and just have $this->(The Object)->(TheMethod)(); And so, If you see my Controller class, libraries are instantiated as $this->Object which works perfectly. If from, within my controller I was to load the Model class. For example, $this->Loader->Library('Model'); when that model becomes instantiated, even though an extension of the Base class, I cannot use the libraries I instantiated in my controller. And of course there is a Fatal Error: Fatal error: Call to a member function UserAgent() on a non-object Code: [Select] <?php class Base { private static $Instance; public function Base() { self::$Instance =& $this; } public static function &GetInstance() { return self::$Instance; } } function &GetInstance() { return Base::GetInstance(); } Code: [Select] <?php class Controller extends Base { function Controller() { parent::Base(); $this->Initialize(); } function Initialize() { $Array = array( 'Uri', 'Loader', 'Router', 'Database', ); foreach($Array as $Object) { $this->$Object = loadClass($Object); } } } Code: [Select] <?php class Model extends Base { function Model() { parent::Base(); echo $this->Input->UserAgent(); } } Code: [Select] <?php class Home extends Controller { function Home() { parent::Controller(); } function index() { $this->Loader->Library('Session'); $this->Loader->Library('Model'); $Data = array( 'Controller' => $this->Router->FetchClass(), 'Title' => ucfirst($this->Router->FetchClass()) ); $this->Loader->View('meta',$Data); $this->Loader->View('header',$Data); $this->Loader->View('home'); $this->Loader->View('footer'); } } Any input would be appreciated! Similar TutorialsHi, I have an output of print_r he
Google_Service_Calendar_Acl_Resource Object ( [stackParameters:Google_Service_Resource:private] => Array ( [alt] => Array ( [type] => string [location] => query ) [fields] => Array ( [type] => string [location] => query ) [trace] => ArrayI am wondering what is the right syntax to create the instance and set the variables? Thanks, Ted I've been looking everywhere for a solution of this but I can't find one...
Basically what I did was created a class named USER.
public class USER{ private static $USER = array(); public function __construct($U='') { // if $U is not entered (=='') then set $U to MY USER ID ($_COOKIE['user']) // do a mysql query by the ID (ala $U) and store the results to self::$USER } public function ID() { return self::$USER['id']; } }This is the code I am running... I do a user profile page that shows different properties of the USER from the database: USERNAME(),ID(),PHONE(),EMAIL(), etc. etc. // creates an instance of a different user (other than myself) $PROFILE = new USER($ID); // $ID: 26 will retrieve USERNAME: Test // create an instance of user class for myself using the cookie holding my id $ME = new USER($_COOKIE['user']) // $_COOKIE['user']: 01 will retrieve USERNAME: Monster echo($PROFILE->USERNAME()); // displays Monster echo($PROFILE->ID()); // displays 01Any idea what I am doing wrong? I would assume that $PROFILE->USERNAME() would display Test and $ME->USERNAME() would show monster. I'm trying to make my register script check the database's IP column and compare it with the user's IP. If the User's IP equals that in the DB column, it should say "Sorry, there is already an account registered with your IP Address. Please log in.", and if there's no IP match, it should allow them to continue with registering. I've been tinkering around with this for a while and I can't seem to figure it out. Any help would be appreciated if ($_SERVER['REMOTE_ADDR'] == mysql_query("SELECT ip FROM users")) { die('Sorry, there is already an account registered with your IP Address. Please <a href="/login.php>log in.</a>'); }else{ echo ''; } I think the problem is with the mySQL query... So, I have what I think is an odd question. I have a function that contains a for loop. Within that for loop, it checks for a new condition and if it is true, it calls the very function it's already in. So, within the for loop inside of function "a", it can call function "a" with new arguments which will then start a new for loop to be "nested" to the previous for loop, in a way. My problem is trying to keep the values of the variables so that once the new for loop (or loops) finish, the previous for loop won't be stopped up by the new variable values that have since changed. Make sense? So, two questions: 1. How do I lock in values that make them unique to that very call of that function and keep them unique through further iterated versions? 2. I imagine, in theory, that for loops stay in memory in state as a new "instance" of that same for loop runs through, right? Basically, is what I'm doing possible in that a for loop calls itself, in essence, to create a new "instance" of that for loop, then when it finishes, have the previous loop continue iterating? For question #1, I've already thought about using variable variables, but that doesn't work because every time the function is called, the variable variable will change to new values based on the new arguments and instantiating the function again. I'm kind of looking for a way to make unique "instances" of a method that don't mess with future calls to that method and where future calls don't mess with currently iterating loops in that method. Phew, I think I confused myself. Thanks for any help. Hey Guys. I have a shopping cart script that loops through the shopping cart session array and assigns values to the property of a class. For some weird reason the subtotal property only works when I use the self keyword. If I use the $this-> instance variable the sub total does not get assigned the subtoal price. Its just NULL.
Does anyone have any suggestions as to why it may not be working.
Below is a quick copy and paste of my code. Please be aware that some there may be some syntax mistakes as a result to copying and pasting part of my code that is relevant to this issue. Thanks!
class CoreCartFunctions { protected static $subtotal; protected $menu_item_price = NULL; public function GetMenuItem() { //self:items is the cart session array that is initilized in a construct method //Assign the values for each cart array foreach (self::$items as $menu_item_id_session) { $this->menu_item_price = getItems($this->menu_item_id,"menu_item_price")*$this->item_qty; self::$subtotal += $this->menu_item_price; //Does not work with the following ---> $this->subtotal += $this->menu_item_price; } } Hey, I'm trying to save a MySQL-Link source as an instance variable in my query class. The problem is that MySQL sees it as an invalid MySQL-Link (supplied argument is not a valid MySQL-Link resource). What I'm I doing wrong? //Walle Code: [Select] private $connection; //Construct public function __construct(&$connection) { $this->connection = $connection; } //Where the error occurs public function exe_query($sql) { $result = mysql_query($sql, $this->connection); if(!$result) { throw new Exception(mysql_error()); } return $result; } Hello, I need to find the target html address within some raw html. I know it lies between Needle 1 and Needle 2 below. Needle 1: </span></a> <a href=" Needle 2: " rel="nofollow"><span class=pn><span class=np>Next »</span></span></a></div> Nornally I would just use the explode() function but my headache is that there are many instances of Needle 1 in the raw html code and I want my output array always have the same number of elements. However I do know that my target html address is directly after the last instance of Needle 1. How should I go about splitting the html code into an array that always has 3 elements? I'd like the first element to include code up to and including the last instance of Needle 2, the 2nd element to have the target html address, and the 3rd element to have Needle 2 and any following code. Thanks for any pointers (my main struggle is identifying the last instance of needle 1), Thanks, Stu Hope someone can help, I am trying to add up all the values of a variable in a PHP while loop and have tried several approaches but none seem to work. Hopefully someone can point out what the correct method is. I've set up some code to pull the pay rate from a MySQL table, and then calculate that person's earnings based on the amount of time they spend on a particular job. That works fine:
However there may be a number of jobs for different people with different rates, so I want to add all of these up and output the total. So for example if I had values of 125.00, 35.50 and 22.75 I want to show 183.25 as the total. So I tried a few things I found on forums on the subject:
That didn't work so I tried another method that someone suggested:
The 2nd method outputted just the last individual value, the 1st method didn't work at all. Does anyone have a working method that can be used to do this? Thanks Hi, I'm just wondering if there's any way to use the Limit to limit a search to the first instance of multiple items in one column? Eg, in a table called news I might have: subject content general general news1 general generalnews2 faq faq1 faq faq2 general generalnew3 When I do Code: [Select] SELECT * FROM news ORDER BY content DESC LIMIT 0,1(same if I substitute the word subject for content in the line above) ...I get just the first item. Ie: subject content general generalnews1 How would I go about getting the first instance of each subject and its contents to appear? Ie: subject content general generalnews1 faq faq1 Thanks, Dave json_decode returns a stdClass Object. Is there any way where I can get instance of my class instead of the same? I mean If I json_decode the below string then it will provide me instance of stdClass and not instance of Person class {"name":"a"} How to achieve the same? Thanks in advance CSJakharia I know you can use str_replace to replace a value with another value, or an array of values with an array of other values. What I'd like to do is replace each instance of a single value with an array of values which get iterated through for each instance found. Think prepared statements that you don't have to call setString or setInt on. Here's a made up example. Code: [Select] $db->query = 'SELECT * FROM users WHERE user_name = ? AND user_role = ?; $db->params = array('hopelessX','admin'); $db->executeQuery(); //this contains a call to a private function that does the replace I have everything else working except this. It works if I specify an array of values to replace and do something like below, but I was hoping to not have to support that method of replace if I didn't need to. Code: [Select] $db->query = 'SELECT * FROM users WHERE user_name = :name AND user_role = :role; $db->replace = array(':name',':role'); $db->params = array('hopelessX','admin'); $db->executeQuery(); //this contains a call to a private function that does the replace I can do it that way if I need to or I could make some overly complicated thing that finds each instance of the question mark, replaces it with a unique value and then adds that unique value to a replace array similarly to the method in code block two but that defeats to the purpose of making this simple database adapter in the first place (although it was mostly just for fun anyway). Anyway, if anyone has any advice and knows of a simple means to achieve this goal that would be much appreciated. Thanks in advance I have a table that contains the schools in my system: schools id name location ... Then, I have three tables that use the id of this table: schoolAdmins schoolID schoolContests schoolID students schoolID When I go to delete a school from my system, I want to check to see if that school is connected to any of these three other tables first. This is what I tried (but obviously failed because I'm here) where I'm passing the query the $studentID in question: SELECT * FROM schoolAdmins, schoolContests, students WHERE (schoolAdmins.schoolID = $schoolID) OR (schoolContests.schoolID = $schoolID) OR (students.schoolID = $schoolID) I'm really new to the concept of querying multiple tables in a single statement, so I'm just kind of guessing at this point. Thanks in advance. Hi All
I have not really played around with PHP in ages so I am having a hard time trying to figure out the best way to proceed. Anyhow... what I need to get done is to take a singleton pattern core database class that has a extended driver based class (ie; the type of database server the connection is connecting to), and build a new class that dynamically handles as many driver based connections that are called using a single instance. As a side note, I tried PDO but it only supports a single driver per class instance, and then each of those connections cannot not have their on set of properties that relate to each connection. Anyway, I was thinking that the best way to handle all the driver specific connections, is to hand out a 'unique hash reference' that points to an array of connection objects and the object properties. then when the client runs any sql function they pass the 'unique hash reference' which the class then returns the object and it properties that will be used by the class to call up the driver specific sql function that was requested by the client. So what do you all thing about that....
TIA stephanieT
PS...
I reason i need this is because I need to update up 25 different databases based on data stored on all the databases and not all of the database servers are of the same type, (ie; MSSQL, Oracle, MySQL, MariaDB, berkeley DB, postgres, sqlite2,3, etc, etc)! Edited January 16, 2019 by StephanieTI have a scenario in PHP, i need a smart way: 1. I run one process on background forever, scheduler.php - done 2. User on the web submit their task in DB to be processed by the above process(scheduler.php) - done 3. scheduler.php read the db after every 1 sec, looking for user's task. Problem: Ideally, if it founds like 10 or more tasks it should process them concurently(in parallel)..i.e it should not wait one task to be fully executed so as to run the next one as one task might take a very long time to be fullu executed. I would do like exec("nohup php <path>/file_name.php >> /dev/null 2>&1 &"), but if i have alot of tasks this will create zombie processes. Any smart way to do this will be highly appreciated! I have
class MyProductClass { function computeProductA() { doSometing(); } function computeProductB() { doSometingElse(); $this->computeProductCommon(); } function computeProductC() { $this->computeProductCommon(); } function computeProductCommon() { } }And I was wondering ... does it make sense to move out product-specific functions into their own classes and then have them extend MyProductClass. While I think it makes sense to me from an aesthetic point of view, and that I get to use object oriented principles, I could not answer myself as to "Why" I would do that. So, why? Why would I do that, and should I? Right now in the code, various product specific classes instantiate MyProductClass and just use their specific and generic functions, as needed. Edited by dennis-fedco, 15 December 2014 - 09:55 AM. Hello, I have two classes: Code: [Select] abstract class Serializable { public function serialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } class ToSerialize extends Serializable { public function otherSerialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } $foo = new ToSerialize(); $foo->serialize(); //This will return one thing $foo->otherSerialize(); //This will return something different Why does this happen? Hey again, I hope you guys don't get annoyed with my noob questions. I was reading the guide here on the site about OOP, and on the section related to inheritance it makes a "Dog" class, after giving it an attribute and a method it then creates the "Animal" class using "extends" and expands on the methods. Then after that here is the paragraph I'm looking at now. "Class Animal is unaware of the fact that it is being extended; there are no references to Dog whatsoever. Say Animal extended another class called LifeForm, and I instantiated Animal, only methods and properties of Animal and LifeForm would be included in the object." To me, this sounds like if I were to create this "LifeForm" class by further extending the "Animal" class, I would not be able to access any of the attributes and methods that were in "Dog," only the ones that were in Animal and any that I put in LifeForm itself. But, I was playing with the code and I can call an attribute from Dog in LifeForm. So, am I reading the post wrong or am I coding wrong? Code: (php) [Select] <?php //Class Dog// class Dog{ public $hungry = 'Hell yeah!'; public $test = 'Affirmative!'; function eat($food){ $this->hungry = 'not so much.'; } } //Class Animal// class Animal extends Dog{ function eat($food){ if($food === 'cookie'){ $this->hungry = 'not so much'; }else{ echo 'Barf! I only like cookies!'; } } } //Class LifeForm// class LifeForm extends Animal{ function eat($food){ } } //Program Variables// $dog = new Dog; $LifeForm = new LifeForm; //Program Code// echo $LifeForm->test; ?> My assumption was that I am able to call that attribute because of the 'public' in front of it, but all the attributes in the examples are also public. Thanks guys! Context. Class AbstractTenantEntity's purpose is to restrict access to data to the tenant (i.e. account, owner, etc) that owns the data. Any entity which extends it will have the TenantId added when created and the TenantId in the WHERE clause for all other requests. Tenant typically does not have collections of the various entities which extend AbstractTenantEntity, but does for a few of them do. When using annotation, I handled it by applying Doctrine's AssociationOverride annotation to the extended classes which should have a collection in Tenant. use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() */ class Tenant { /** * @ORM\OneToMany(targetEntity=Asset::class, mappedBy="tenant") */ private $assets; // Other properties and typical getters and setters }
use Doctrine\ORM\Mapping as ORM; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required * @ORM\ManyToOne(targetEntity=Tenant::class) * @ORM\JoinColumn(nullable=false) */ protected ?Tenant $tenant = null; // Typical getters and setters }
use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() * @ORM\AssociationOverrides({ * @ORM\AssociationOverride(name="tenant", inversedBy="assets") * }) */ class Asset extends PublicIdTenantEntity { // Various properties and typical getters and setters }
So, now I am changing from annotations to attributes, and modified AbstractTenantEntity as follows: use Doctrine\ORM\Mapping\ManyToOne; use Doctrine\ORM\Mapping\JoinColumn; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required */ #[ManyToOne(targetEntity: Tenant::class)] #[JoinColumn(nullable: false)] protected ?Tenant $tenant = null; // Typical getters and setters } Next I went to modify Asset and realized that there didn't appear to be an attribute for AssociationOverride. I found a little discussion on the topic on github but couldn't find any resolution. Question Can inheritance be used with PHP 8 attributes where the property is defined in the parent class and the attribute is applied in the child class? Googling php 8 attributes inheritance didn't provide anything and thus I expect the answer is no but thought I'd ask. Thanks
EDIT. Maybe Doctrine does have an attribute version: https://github.com/doctrine/orm/blob/2.9.x/lib/Doctrine/ORM/Mapping/AttributeOverride.php EDIT2. Actually don't think so Edited July 30 by NotionCommotionI am using API-Platform, Doctrine, and Symfony with entities that utilize class type inheritance to extend an abstract entity. I've been running into one issue after another primarily related to the serialization process (serialization groups, parent annotations not propagated to the child, etc), and while I am sure user error on my part is part of the culprit, it appears that API-Platform and potentially Symfony and Doctrine don't fully support entity inheritance. My reason for thinking so is the incredibly sparse amount of documentation on the subject and remarks on quite a few github issues posts and other blogs how it is "bad practice". For instance, say I have Mouse, Cat, and Dog which all extend AbstractAnimal, and each has a bunch of common properties such as birthday, weight, etc, and methods such as eats(), sleeps(), etc. Sorry in advance for using hypothetical entities but I don't think doing so distracts. I like how inheritance allows me to keep all common properties in a single table, but can let that go. More importantly, the subset mouse, cat, and dog table shares an ID from the animal table allowing me to associate all animals to some other table (i.e. many-to-one to person whether they are their pet or many-to-many to country whether they are native to a country), and to retrieve a list of animals and filter by some property or type as needed without a bunch of unions. To me, this sounds like inheritance, but if the products I am using don't support it very well, it doesn't matter. First question. Is entity inheritance considered bad practice? And even if not, is it common for frameworks to limit their level of support for them? If so, what can I do about it? Maybe favor composition over inheritance? Okay, great, I now have a single animal table which makes all my SQL concerns issues go away and I am pretty confident that my serialization issues will also go away. All I need to do is inject each animal with some "thing" to make them a mouse, cat, or dog. But what do I call this thing? I've struggled with this topic for a while and asked the same question regarding how to deal with BarCharts, PieCharts, GaugeCharts, LineCharts, etc all being charts but all acting slightly differently, and never really came to any conclusion. For a non-hypothetical scenario, I have BacnetGateway and ModbusGateway which extend AbstractGateway. Okay, this one is easy and I change to just having a Gateway and inject either BacnetProtocol or ModbusProtocol. For another non-hypothetical scenario, I have PhysicalPoint which represents some real environmental parameter, VirtualPoint which represents combining one or more PhysicalPoints or VirtualPoints, and TransformedPoint (feel free to provide a better name) which represents performing some time function such as integrating over a given time. Currently, they all extend AbstractPoint, but if I was trying to do so with composition, I could inject PointType but don't think doing so makes sense. For my hypothetical scenario, do I make a DNA interface and inject an Animal with DogDNA to get a dog? I really need to get my head around this once and for all. Thanks Hi, After a long time I start php again to do some stuff and using OOP concept for the first time and getting this below error Code: [Select] PHP Fatal error: Class 'SystemConfig' not found in /home/tanveer/Workspace/EmailTest/webapp/classes/MailParser.class.php on line 12, referer: http://localhost/EmailTest/public_html/index.php My project directory structure is as follows: Code: [Select] \webapp: |- classes |- MailParser.class.php |-DatabaseConnect.class.php |-SystemConfig.class.php \public_html: |-header.php |-footer.php |-gencsv.php |-stat.php \css |-style.css \images index.php And the php code file that I am trying to make work is as follows: class MailParser extends SystemConfig { /* Reads the files passed line-by-line * @param $fileName */ public function readFiles($fileName){ $fileHandler = fopen($fileName,'r'); while ($line = fgets($fileHandler)) { echo $line."<br />"; } fclose($fileHandler); } /* Traverse the user specified directory * @param $dirPath */ public function traverseDirectory($dirPath) { echo $dirPath; $sentFolderPath = new SystemConfig(); $sentFolderPath->getSentMailFolder(); $totalDirPath = $dirPath."/".$sentFolderPath; echo $totalDirPath; $io=0; if ($handle = @opendir($dirPath)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $newdir = ""; $filetext = ""; if (!is_file($dirPath."/".$file) or is_dir($dirPath) ) { $io++; $newdir.= $dirPath."/".$file."/"; print $newdir."<br />"; $this->traverseDirectory($newdir); if(is_file($dirPath.$file)) { $text = str_replace('//','/',"".$dirPath.$file."\n"); } } } } closedir($handle); } } } $rmf = new MailParser(); $rmf->traverseDirectory($_POST["dirpath"]); ?> |