PHP - Extending Php Class
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 Similar Tutorialscould 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'); 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? 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"; } } 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 ? 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 mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Hi Can you call Class A's methods or properties from Class B's methods? Thanks. 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 If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many 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 I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? How does one go about using one class inside another? For example, building a class that does some series of functions, and uses a db abstraction layer class in the process? Hi all, I have two classes. Registration and Connection. Inside a registration.php I include my header.php, which then includes my connection.php... So all the classes should be declared when the page is loaded. This is my code: registration.php: <?php include ('assets/header.php'); ?> <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($data, $table){ foreach($this->fields as $key => $value){ mysql_query("INSERT INTO graphs ($this->fields) VALUES ('$data[$key]')"); } mysql_close($connection->connect); } function validateFields(){ $connection = new connection(); $connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data, $this->table); } } $registration = new registration(); $registration->validateFields(); ?> <?php include ('assets/footer.php'); ?> At this point I cannot find my connection class defined on another included/included page. $connection = new connection(); $connection->connect; config.php (included within header.php) <? class connection{ public $dbname = '**'; public $dbHost = '**'; public $dbUser = '**'; public $dbPass = '**'; public $connect; function connect(){ $this->connect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die ('Error connecting to mysql'); mysql_select_db($this->dbname, $this->connect); } } ?> Any ideas how to call it properly? I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability. I have a class in which I have a function called connection. I am now trying to call this function from another class, but it will not work. It works if I put the code in from the other function rather than calling it but that defeats the purpous. class locationbox { function location() { $databaseconnect = new databaseconnect(); $databaseconnect -> connection();{ $result = mysql_query("SELECT * FROM locations"); while($row = mysql_fetch_array($result)) // line that now gets the error, mysql_fetch_array() expects parameter 1 to be resource, boolean given //in { echo "<option>" . $row['location'] . "</option>"; } } }} Well the title may seem a bit confusing, but heres an example: Code: [Select] <?php class User{ public $uid; public $username; protected $password; protected $email; public $usergroup; public $profile; public function __construct($id){ // constructor code inside } public function getemail(){ return $this->email; } public function getusergroup(){ return $this->usergroup; } public function getprofile(){ $this->profile = new UserProfile($this->uid); } } class UserProfile(){ protected $avatar; protected $bio; protected $gender; protected $favcolor; public function __construct($id){ // constructor code inside } public function formatavatar(){ // avatar formatting code inside } public function formatusername(){ // format username? } } ?> As you can see, the User class(an outer class) has a property called Profile, which can be instantiated as a UserProfile object(an inner class). The two objects have distinct functionalities, but there are times when the UserProfile object needs to access property and methods from the user object. I know its easy for outer class to access methods from inner class by using the single arrow access operator twice, but how about the other way around? Lets say from the above example the userprofile can format the username displayed to the screen by adding a sun to the left of the username if the usergroup is admin, a moon if the usergroup is mod, and nothing if its just a member. The usergroup property is stored in the outer class, and can be accessed with this $user->getusergroup() method only. I know I can always do the hard way by passing a user object to the method's argument, but is there an easier way for the inner class UserProfile to access properties/methods for outerclass User? If so, how can I achieve that? im trying to learn more on OOP so decided to try this code: class asf { public $_template; public function __construct() { $this->_template = new newTemplate; } } class newTemplate { public function setTemplate($template) { global $asf; $asf->_template = $template; } public function getTemplate() { global $asf; return $asf->_template; } } $asf = new asf; $asf->_template->setTemplate('default'); echo $asf->_template->getTemplate(); setTemplate() works but i get the following error on getTemplate(): Code: [Select] Call to a member function getTemplate() on a non-object can anyone explain why and let me know how to fix it? Thanks. Hi I can't seem to return the MAX position of my data in the MYSQL database. Class Code: [Select] public static function find_last_pos(){ global $database; $sql = "SELECT max(position) as max_position FROM ".self::$table_name." LIMIT 1"; $result_array = self::find_by_sql($sql); return $result_array[0]->max_position; } HTML Code: [Select] $POS = Blog_categories::find_last_pos(); echo $POS; Where am I going wrong? *note, the class works fine if I select * rather than max() Thanks |