PHP - Class Organization
I've made several classes which pertain to product information. They are as such:
1) class.Product.php 2) class.WineProduct.php 3) class.ProductReview.php 4) class.ProductAward.php Currently class.WineProduct.php extends class.Product.php; ProductReview and ProductAward are just included in the Product class - this I know is wrong because when I try to run a function from within that class I get the error: Quote Cannot access parent:: when current class scope has no parent Here's a sample of the offending code: Code: [Select] $wine = new WineProduct(); $wine->AddAward('Gold'); // This is the bad line: foreach($wine->awards as $awd) $awd->SaveToDB(); The SaveToDB function uses parent::barcode in an SQL query. The barcode is a property of the Product class. I know this has something to do with the include() statements...but what SHOULD I have done? Similar TutorialsI have this interesting problem, I think I know how to do it.
In a java class I took there was a lab on swapping the values of variables and if there were two variables, you needed a third temporary value holder.
So this project I'm working on has a row output, currently the individual values are outputted as a concatenated string but ideally they would be independent rows with accompanying buttons.
One of those buttons is a ^ symbol, when you press this, ideally the row is moved up in ID putting the previous ID in front or ahead.
The problem is that the ID's / rows are not necessarily in sequential order.
So, when I recall a set of rows that have random sequential values for example, 2, 5, 27, 41, 43
and those are outputted by themselves, now becoming 0,1,2,3,4 respectively or 1,2,3,4,5
So when I try to move 43 to position 2, that's 4 positions away or 4 clicks of the ^ button.
Now how do you deal with that 4 difference and the difference of 41... ? thereby, when the initial set of rows are recalled again, the order is now, 43, 5, 27, 41, 2 Of course the ID I think remains the same but the data is switched... ? yeah I have to draw some pictures, but this isn't a current problem to fix, later on down the road after I update the interface.
here is a drawing to explain, I'm more of a visual person
wp_20150112_05_27_16_pro.jpg 59.67KB
0 downloads
Any ideas would be appreciated, otherwise I will post my solution when I come to it. Or I don't figure it out and find one.
thanks
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? 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 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 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? 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. 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 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? 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 I would like to create a class that would automatically create a table / box with backgrounds, borders and images already in place so when I want to use that table repeatedly on my site I can just call on the class and fill the table from the database. I am fairly new to php, any help would be appreciated Thanx Rab ok - I lifted some code to help identify the client's browser (damn iphone doesn't like my "select" tag). The code was this class definition and was followed by a couple lines showing how to use it. Here are the two lines: Code: [Select] $browser = new Browser ; echo "Using: $Browser->Name $Browser->Version" ; When I include the class and add these two lines to my script all I get is the word "using:' displayed. Is it possible that the writer of this code left something out? I don't know what the syntax of the "x->y" references are, but shouldnt' there be a call to functions within the class? Okay, so I want to take a stab at my first PHP class. Here is what I want it to do, but I'm not sure where to begin?! I have an HTML form in my index.php file, and when the user clicks "Register", I'd like to have registration.php which will contain the class Registration take what was entered in the form and print it out on the user's screen. This is an academic example, but it will get my feet wet! So, some questions... 1.) If registration.php is basically my Registration class, then where do I "instantiate" the class to create a "registration object"? 2.) How do I pass what was entered into the form to my registration class? Can you pass arguments to a class while you are instantiating it? Or do I instantiate the class, and then pass values to the object? Or do I let the object somehow get the values? 3.) I assume if I make it this far, then I can display the values by just having echo statements in the class/object, maybe as a method? Thanks, TomTees hey guys im wondering the best way to call a class without repeating code for instance i load my classes using the autoload function but when i want to use my FORM class i have to set it as a global to before being able to call a function is there a way without doing this all the time function __autoload($class_name) { include $class_name . '.php'; } controller class controller extends mysql { public function __contruct() { global $form; $model = new model(); // loads automatically $form = new forms(); } } class model { function test() { global $form; // repeating code again to call forms $form->validate_field('test'); } } as you can see in the model i have to set the form global as in controller before calling a function....is there a better way that what im doing please? if you dont understand please let me know thank you Here it is, comments please guys! THnkas <?php class buddyList { // PenpalA = current logged in member; // PenpalB = member to add to list; // name = name of member to add to list var $buddyList; //an array of buddies var $buddies; //an amount var $loggedUserID; function __construct(){ $this->loggedUserID = $_ENV['loggedMemberID']; } function add($penpalB) { //check if row already exists $sql = "SELECT id FROM buddy WHERE `PenpalA` = '$this->loggedUserID' AND `PenpalB` = '$penpalB' AND `status` = 1"; $mysql = new mysql(); $mysql->query($sql); if( mysql_num_rows( $mysql->result ) < 1 ){ //if row doesnt exist add new row $sql = "INSERT INTO `buddy` (`penpalA` ,`PenpalB`) VALUES ('$this->loggedUserID','$penpalB');"; $mysql = new mysql(); $mysql->query($sql); $tempMember = new member($penpalB); //display success message echo '<span class="pint2"><strong>'.PROFILEadded_buddy_before.$tempMember->name.'</strong> '.PROFILEadded_buddy_after.' <a style="color:#ffffff" href="http://localhost/penpalparade/buddy'.( in_array($lang,$_ENV['supportedLanguages']) ? "/".$lang : $nothing).'">'.PROFILEsee_buddy_list.'</a> </span>'; } } function remove($penpalB) { $sql = "UPDATE buddy SET `status` = 0 WHERE `PenpalA` = '$this->loggedUserID' AND `PenpalB` = '$penpalB'"; $mysql = new mysql(); $mysql->query($sql); $tempMember = new member($penpalB); // display success message echo '<span class="pint2"><strong>'.PROFILEremoved_buddy_before.$tempMember->name.'</strong> '.PROFILEremoved_buddy_after.' <a style="color:#ffffff" href="http://localhost/penpalparade/buddy'.( in_array($lang,$_ENV['supportedLanguages']) ? "/".$lang : $nothing).'">'.PROFILEsee_buddy_list.'</a></span>'; } function build() { $this->buddyList = array(); $sql = "SELECT `PenpalB` FROM buddy WHERE `PenpalA` = '$this->loggedUserID' AND `status` = 1"; $mysql = new mysql(); $mysql->query($sql); $i = 0; while($row = mysql_fetch_array($mysql->result)){ $this->buddyList[$i] = $row['PenpalB']; $i++; } $this->buddies = $i; } function display() { //build table echo '<table border="1" width="100%">'; echo '<tr><td align="center"><strong>'.MISCbuddy_name.'</strong></td>'; echo '<td align="center"><strong>'.MISCbuddy_last_online.'</strong></td>'; echo '<td></td><td></td></tr>'; //display buddies for ( $counter = 0; $counter <= $this->buddies-1; $counter += 1) { $tempMember = new member($this->buddyList[$counter]); echo '<tr>'; //start row echo '<td align="center">'; echo '<a href='.(in_array($lang,$_ENV['supportedLanguages']) ? $lang."/" : $nothing).HEADlanguage_exchange.'/id/'.$tempMember->id.'">'.$tempMember->name.'<br />'; $tempMember->displayPhoto(82); echo '</td>'; echo '<td align="center">'.MISCbuddy_ago_before.time_since($tempMember->lastOnline).MISCbuddy_ago_after.'</td>'; echo '<td align="center"><a href="http://localhost/penpalparade/email.php?id='.$tempMember->id.'&email=yes'.(in_array($lang,$_ENV['supportedLanguages']) ? '&lang='.$lang : $nothing).'">'.MISCbuddy_message.'</a></td>'; echo '<td align="center">'; ?> <form action="javascript:void(0);" method="post" onsubmit="if( confirm('<?=MISCbuddy_remove_confirm?>') ){ document.getElementById('removePenpal<?=$tempMember->id?>').innerHTML='<?=MISCbuddy_remove_change?>';document.getElementById('ajax-loader<?=$tempMember->id?>').style.display = 'block';window.location = 'buddy.php?remove=<?=$tempMember->id?><?=(in_array($lang,$_ENV['supportedLanguages']) ? '&lang='.$lang : $nothing)?>' }else{ }"> <div style="display:inline;" id="removePenpal<?=$tempMember->id?>"><input type="submit" value="<?=MISCbuddy_remove?>" /></div> <div style="display:none;" id="ajax-loader<?=$tempMember->id?>"><img class="ajaxLoader" src="mages/ajax-loader.gif" alt="removing..."/></div> </form></td> <?php echo '</tr>'; //end row } echo '</table>'; } } ?> |