PHP - Extending Classes
Im having problem extending a class.
Code: [Select] <?php // Parent class class Profile { protected $id, $result, $info; protected function get_id() { return $_GET['id']; } protected get_info() { $id = $this->get_id(); $result = mysql_query("SELECT * FROM profiles WHERE id = '$id' "); return mysql_fetch_array($result); } public get_fname() { $info = $this->get_info(); return $info['fname']; } public get_lname() { $info = $this->get_info(); return $info['lname']; } } // Child class class Profile_new extends Profile { protected get_info() { $id = $this->get_id(); $result = mysql_query("SELECT * FROM new_profiles WHERE id = '$id' "); return mysql_fetch_array($result); } } // Webpage $profile = new Profile_new; $first_name = $profile->get_fname(); $last_name = $profile->get_lname(); ?> For some reason I still getting first + last names of people from the profiles table, and not from the new_profiles table. How can I fix this ? 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? Hi Not sure if I am on the right track here but what I am trying to do is set a variable in the parent class and for this to be accessible in the child. class layout { public $site_id; function __construct($site_id) { $this->site_id = $site_id; } function get_flags() { return new flags($this); } function top_nav() { return new top_nav($this); } } class top_nav extends layout { function __construct(){ } function display_site_id() { echo $this->site_id; } } class flags extends layout { function __construct(){ } function display_site_id() { echo $this->site_id; } } $site_id = 1; $layout = new layout($site_id); $flags = $layout->get_flags(); $nav = $layout->top_nav(); var_dump($layout); var_dump($flags); var_dump($nav); This gives me the following output object(layout)#1 (1) { ["site_id"]=> int(1) } object(flags)#2 (1) { ["site_id"]=> NULL } object(top_nav)#3 (1) { ["site_id"]=> NULL } Where I would have expected object(layout)#1 (1) { ["site_id"]=> int(1) } object(flags)#2 (1) { ["site_id"]=> int(1) } object(top_nav)#3 (1) { ["site_id"]=> int(1) } but I am new to OOP and might be doing things completely wrong Thanks for your help Regards could anyone advice how to extend the php class who contains variable? sample below does not work. Code: [Select] class test1 extends test2($index){ public function output($index){ echo $index; } } class test2{ public function __construct($index){ echo $index; } } $test = new test1; $test->output('My Test2'); $test->test2('My Test1'); This scripts works fine however I want to extend the if check against the database so that somehow instead of just telling the user that there was a problem on the on the form page I can tell them which was the actual problem so how could I extend it so that I can tell the user if it was the contentpage or the shortname that was the problem. if (isset($_POST['editcontentpage'])) { $contentpage = mysqli_real_escape_string($dbc, $_POST['contentpage']); $shortname = mysqli_real_escape_string($dbc, $_POST['shortname']); $contentcode = mysqli_real_escape_string($dbc, $_POST['contentcode']); $linebreak = mysqli_real_escape_string($dbc, $_POST['linebreak']); $backlink = mysqli_real_escape_string($dbc, $_POST['backlink']); $showheading = mysqli_real_escape_string($dbc, $_POST['showheading']); $visible = mysqli_real_escape_string($dbc, $_POST['visible']); $template = (int)$_POST['template']; $contentpageID = (int)$_POST['contentpageID']; $query = "SELECT * FROM `contentpages` WHERE `contentpage` = '".$contentpage."' OR `shortname` = '".$shortname."'"; $result = mysqli_query ( $dbc, $query ); // Run The Query $rows = mysqli_num_rows($result); if ($rows == 0) { $query = "UPDATE `contentpages` SET `contentpage` = '".$contentpage."', `shortname`='".$shortname."', `contentcode`='".$contentcode."', `linebreaks`='".$linebreak."', `backlink`='".$backlink."', `showheading`='".$showheading."', `visible`='".$visible."', `template_id`='".$template."' WHERE `id` = '".$contentpageID."'"; mysqli_query($dbc,$query); echo "good"; } else { echo "bad"; } } I am working on a REST application which is intended to be used with various CMS’s (Drupal, WordPress, etc). Each CMS installation passes a unique GUID in the header to identify the organization so that the organization's individual data is utilized. I’ve since realized I need some basic way to identify the individual user for at least two reasons: The API provides a help desk where individual users can ask questions and get responses (not real time). There is some need for user access/privileges (I suppose this could be CMS side if necessary).Instead of inputting users both into the API as well as the CMS, the organization should be responsible for entry only through the CMS. They will add users as appropriate for the given CMS and then another page on the CMS will list all the CMS users and provide a way to set whether they are authorized to access the API as well as their access level. The remaining of this post is kind of what I am thinking, but I am open to change. When the CMS gives a user access to the API for the first time, a cURL request is made to the API and a unique key is returned and the CMS will save it as being associated with the given user. Note sure if this should be an incrementing number on a per organization basis or another GUID, and if a GUID whether it should be passed along with the organization’s GUID or replace it. Also, not positive, but thinking that user data (name, email, etc) should not be given to the API as it might be difficult to keep them synchronized. If a user’s access level is changed on the CMS or their access is removed, the user’s GUID is passed to the API and the work is done on the API. If the user is removed, they are not deleted from the API’s database but just tagged as deleted. Before performing step 1, the CMS should first perform a query requesting all users who are tagged as deleted and is responsible to determine whether a new user should be added or an existing user should be reinstated. Alternatively, I can make the API responsible for doing so, but then it would need to have stored various data to identify whether the user was previously instated which might result in the synchronization issue I described in step 1.Any comments, potential pitfalls, or recommendations would be appreciated. I have these two classes: Code: [Select] <?php class A { private $id; public function __construct() { $this->id = '11111'; } public function getProperty($prop) { return $this->$prop; } }?> Code: [Select] <?php class B extends A { private $message = "Nope, can't see it"; public function __construct() { parent::__construct(); $this->message = "Yep, I can see it"; } }?> I tried this, but it just outputs the id (the first call) Code: [Select] $class = new B; echo $class->getProperty('id'); echo $class->getProperty('message'); Why is that? I thought I could use a parent method on a child property.. *EDIT* Using a public or protected visibility on the message property gets me the output I expect...how come? 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. 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? 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 ? 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 ? 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! 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')? 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. 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! Hello, maybe back to basics, but [PHP] pobierz, plaintext 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
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. I am seriously trying to wrap my head around abstract classes, but the more I try to understand it the more I get confused.
I've even dug out a book by Larry Ullman to no avail.
Here's the example in the book:
Shape abstract class
<?php # Script 6.1 - Shape.php /* This page defines the Shape abstract class. * The class contains no attributes. * The class contains to abstract methods. * - getArea() * - getPerimeter() */ abstract class Shape { // No Attributes to declare. // No constructor or destructor defined here. // Method to calculate and return the area. abstract protected function getArea(); // Method to calculate and return the perimeter. abstract protected function getPerimeter(); } // End of Shape Class.Triangle class: <?php # Script 6.2 - Triangle.php /* This page defines the Triangle class. * The class contains two attributes: * - private $_sides (array) * - private $_perimeter (number) * The class contains three methods. * - __construct() * - getArea() * - getPerimeter() */ class Triangle extends Shape { // Declare the attributes: private $_sides = array(); private $_perimeter = NULL; // Constructor: function __construct($s0 = 0, $s1 = 0, $s2 = 0) { // Store the values in the array: $this->_sides[] = $s0; $this->_sides[] = $s1; $this->_sides[] = $s2; // Calculate the perimeter: $this->_perimeter = array_sum($this->_sides); } // End of constructor. // Method to calculate and return the area: public function getArea() { // Calculate and return the area: return (SQRT( ($this->_perimeter/2) * (($this->_perimeter/2) - $this->_sides[0]) * (($this->_perimeter/2) - $this->_sides[1]) * (($this->_perimeter/2) - $this->_sides[2]) )); } // End of getArea() method. // Method to return the perimeter: public function getPerimeter() { return $this->_perimeter; } // End of getPerimeter() method. } // End of Triangle Class.and to execute in finding the area and perimeter of a triangle: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Abstract Class</title> </head> <body> <?php # Script 6.3 - abstract.php // This page uses the Triangle class - (Script 6.2), which is derived from Shape (Script 6.1) // load the class definitions: require('Shape.php'); require('Triangle.php'); // Set the triangle's sides: $side1 = 5; $side2 = 10; $side3 = 13; // Print a little introduction: echo "<h2>With sides of $side1, $side2, and $side3...</h2>\n"; // Create a new triangle: $t = new Triangle($side1, $side2, $side3); // Print the area. echo '<p>The area of the triangle is ' . $t->getArea() . '</p>'; // Print the perimeter. echo '<p>The perimeter of the triangle is ' . $t->getPerimeter() . '</p>'; // Delete the object: unset($t); ?> </body> </html>What is the point of having an abstract class when it runs fine without it being declared? For example I can take out extends Shape in the Triangle class and it will work just fine? I don't know if If I will ever understand this concept of abstract and interface classes.... Any help in this matter will be greatly appreciated. Thanks John OK, I fooled around with it some more and took out the include('Shape.php') and it spat an out an error stating it wasn't found. So is an abstract class just forcing a person to adhere to the methods being declared in the abstract class? (I'm probably not explaining this right). Edited by Strider64, 03 October 2014 - 10:55 AM. |