PHP - Difficulty With Extended Class
Hello! I'm having trouble with a class that extends another, and I don't think I understand the 'extends' concept properly. I've had my nose in various manuals, but I haven't had any luck figuring it out. Here's a simplified version of my code:
Code: [Select] class Position { private $latitude = 0; private $longitude = 0; public function getLatitude(){ return $this->latitude; } public function getLongitude(){ return $this->longitude; } } class Coordinates extends Position { function __construct($nlat, $nlong){ $this->latitude = $nlat; $this->longitude = $nlong; } } $lat = -123; $long = 44; $coordFirst = new Coordinates($lat,$long); print($coordFirst->getLatitude()); I expect -123 to be printed, but I always get 0 instead. Could someone let me in on what I'm missing here? Thanks a bunch! Similar TutorialsI can not understand why this isn't working, basically it works in one place but not the other I have this in my main class: class phpLive{ public function loadCore(){ foreach(glob($this->location."/core/*/*.core.php") as $coreFile){ $info = (object)pathinfo($coreFile); require_once $coreFile; $pos = strrpos($info->dirname, "/"); $coreMedia = substr($info->dirname, $pos + 1); $className = str_replace(".core", "", $info->filename); $instance = strtolower($className); $this->$coreMedia->$instance = new $className(); } } } On the page that I run (index.php), I use this: $_live->example->loadurl(); which is in a class that looks like this: <?php class ExampleClass extends phpLive{ public function __construct(){ $this->loadCore(); } public function loadurl(){ $this->net->http->getHttp('http://google.com'); } } ?> and I get the following error: Quote Notice: Undefined property: ExampleClass::$net in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 Notice: Trying to get property of non-object in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 Fatal error: Call to a member function getHttp() on a non-object in C:\wamp\www\phpLive\phpLive\plugins\Example\ExampleClass.inc.php on line 7 but, when I run this on the main page: $_live->net->http->getHttp("http://google.com"); The code works just fine. Why doesn't the first one work (the above is the actual code, copy and pasted from my editor)? Hi, I'm having a bit of a problem understanding why I'm not able to use the class I'm extending off of functions. I have a category class that extends off my core class, inside that category class, I'm able to use the core functions and variables inside all custom functions, but not the __construct function. So, to be clear, inside class class, I'm able to call $this->core->function() inside custom functions, such as function add_parent(), but not the __construct function. Why is this happening, what is the logic behind this? This is how I'm extending the class off of the core class: Code: [Select] <?php $core = new core; $parent = new parents; $parent->core =& $core; ?> With this, like I said, I'm able to use all of my core functions inside all other classes called this way, so inside all of the other classes I can do: Code: [Select] <?php $this->core->function(); ?>everywhere besides __construct(). Do I not have the class called properly? Do I need to pass my core class through differently? How can I fix this? Thanks. I'm having a problem with (what I'm almost certain is) variable scope, maybe you can help... So I've got a parent class that, among other things, gets the name of the filepath, explodes this filepath, checks for files with names that mirror that filepath (without the slashes of course), and includes them if they exist: class ParentClass { public $RootFolder; public $PageSections; function __construct() { global $root_folder; $this->RootFolder = $root_folder; //get all directory names... $cleanse = $this->RootFolder; $pagepath = str_replace($cleanse, '', dirname($_SERVER['PHP_SELF'])); $this->PageSections = explode('/', $pagepath); } function RequireIfExists ($sections, $root_folder, $file_name, $file_type) { foreach ($sections as $i){ if (isset($o)) { $i = $o."/".$i; } $file = $root_folder.$i."/".$file_name.$file_type; if (file_exists($_SERVER['DOCUMENT_ROOT'].$file)) { require ($_SERVER['DOCUMENT_ROOT'].$file); echo "<!--".$file." included -->"; //temporary measure to ensure that the file is at least being called. } $o = $i; } } // so, excuting the function // $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); // on some/sub/folder/index.php // will look for somesectionvars.php, somesubsecitonvars.php & somesubfoldersectionvars.php // and include whichever ones exist. } Then there is a child class that utilizes this function, and successfully requires the file. I know the file is coming through because the echo statement on the page shows up in the code, but I cannot get the variables to pass through? <?php class HtmlHead extends PageBlock{ public $PageKeywords; public $PageDescription; public $PageStyles; public $PageScripts; //------------------------ public $SectionKeywords; public $SectionDescription; //------------------------ public $SiteKeywords; public $SiteDescription; public $SiteStyles; public $SiteScripts; //------------------------ public $CatchAll; function __construct() { parent::__construct(); //$this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //I have tried calling the function here with no luck global $site_description, $site_keywords, $section_description, $section_keywords, $xyz; //also made sure to global the variables from the required page $this->SiteDescription = $site_description; $this->SiteKeywords = $site_keywords; $this->SectionDescription = $section_description; $this->SectionKeywords = $section_keywords; $this->PageDescription = $page_description; $this->PageKeywords = $page_keywords; } function Constructor() { $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //Tried calling the function here as well, no luck global $xyz; //global'd the var i want echo "\n<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; echo "\n<!--Sec Keywords are".$xyz."-->"; //Tried to echo the var... //------------------------Rest of code... } } And here is the page that is being required... <?php echo "<!-- 1234 1234 1234 1234 -->"; //test measure to see if/where file is including $section_keywords = "red, secondary"; $section_description = "this is the red section description"; $xyz = "1234"; //test Var to see if there was a naming conflict with the above two.. ?> What am I overlooking this time? Hi All. I am new to PHP, but am learning. I have set myself a mini project to learn some new php and to have some fun! I was hoping that someone would be kind enough to tell me how difficult this would be to achieve, and how they would best suggest to approach it. I want to create a 'availability checker'. I want to create a field where I can input a date. If the date exists in my mysql database then it returns NO, if the date isn't in the database it returns YES. For a admin area I want to have a place to add dates, and maybe some details about these dates. I don't think its overly complicated, but it should still be quite a challenge for me. Any guidance would be greatly appreciated. Thanks Hello everyone. Before I start, I'm relivily new to PHP but have been doing it for a few weeks or so, my latest problem that i've been trying to crack for a few days now is using the "imagecopy" command in php, I'm working on an avatar script that lets users design there own avatar, selecting clothes, hair, eyes, etc. I've only just started and i've ran into a rather large problem so don't seem to be able to move any further, This is the code i have Quote <?php ob_start (); /* background */ $bg = imagecreatefrompng('bg.png'); /* foreground */ $fg = imagecreatefrompng('fg.png'); /* frontground */ $fgg = imagecreatefrompng('fgg.png'); $x = imagesx($bg); $y = imagesy($bg); imagecopy($bg, $fg, $fgg, $x, $y); header('Content-Type: image/png'); imagepng($bg); imagedestroy($bg); imagedestroy($fg); imagedestroy($fgg); ?> However for some reason, probably a simple fault, it's just giving me a broken image link? I'm not sure why it's doing this if you want to see exactly what it's doing please look at http://chat.blastgames.org/index.php Like i say i'm clueless so any help would be much appreciated, Also if anyone knows of any downloadable php avatar scripts that lets you customize things like hair, clothes etc. please tell me, I've been searching for one for a while, Thanks for reading , Any help will be much appreciated. Hi, I have an interface where the user picks an image to upload, it then uploads the original (big) image. That same image then appears but at a reduced size of 150px max height or width, the size is defined in the img tag using height="XX" width ="XX", so it is the same image file, just with its dimensions set in the html. The user then drags a div over the image to crop it. The problem I am having is getting the reference image crop dimensions to translate to the actual full size image. Have attached an image of what the result is. What formula do I need to get it to translate to the bigger image properly? Here is my code: if($_GET['mode'] == 'imageupload') { $imgNumber = $_GET['img'] ; $fileName = strtolower($_FILES["setFile$imgNumber"]['name']) ; $ext = explode('.', $fileName) ; if($ext[1] != 'jpg' && $ext[1] != 'JPG' && $ext[1] != 'jpeg') { echo "<span class='iFOutput'>Can only accept JPG images.<br /><br /> The image you tried to upload was '" . $ext[1] . "'.</span>" ; exit() ; } $tmpName = $_FILES["setFile$imgNumber"]['tmp_name'] ; move_uploaded_file($tmpName, '../uploads/' . $fileName) ; $sizeInfo = getimagesize('../uploads/' . $fileName) ; $resizedArray = imageResize($sizeInfo[0], $sizeInfo[1], 204) ; $finalImageSrc = '../uploads/' . $fileName ; echo '<img id="image' . $imgNumber . '" src="' . $finalImageSrc . '" width="' . $resizedArray[0] . '" height="' . $resizedArray[1] . '" />' ; // SCALED IMAGE FOR CROPPING INTERFACE } elseif($_GET['mode'] == 'imagecrop') { $imgSrc = $_POST['imagePath'.$_GET['img']] ; $thisX1 = $_POST['image' . $_GET['img'] . 'X1'] ; $thisY1 = $_POST['image' . $_GET['img'] . 'Y1'] ; $thisX2 = $_POST['image' . $_GET['img'] . 'X2'] ; $thisY2 = $_POST['image' . $_GET['img'] . 'Y2'] ; $original = imagecreatefromjpeg($imgSrc) ; list($width, $height) = getimagesize($imgSrc) ; if ($width > $height) { $ratio = (150 / $width); } else { $ratio = (150 / $height); } echo $ratio ; $thumbCanvas = imagecreatetruecolor(150, 150) ; $thisX1 = round($thisX1/$ratio) ; $thisY1 = round($thisY1/$ratio) ; imagecopyresampled($thumbCanvas, $original, 0, 0, $thisX1, $thisY1, 150, 150, $width, $height) ; imagejpeg($thumbCanvas, '../uploads/thumbnail.jpg') ; echo '<img id="image' . $_GET['img'] . '" src="' . '../uploads/thumbnail.jpg' . '" />' ; } Hi guys.
I have tried implementing PDO in my php. Basically, I have created a form, which will take a letter, and then pass it to the php file.
My hope was, whatever was entered by the user, whether that was in the guise of being manually entered by them or chosen by a dropbox etc, this would then be able to be used within the LIKE comparison. When I run my file however, I get the following message: Error: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound. I am a little confused by this. I have used $_POST with the HTML form element, and have specified it in the SQL syntax. Can anyone please advise me as to where I am going wrong? How hard would it be to build a basic Online Forum using PHP? (Yes, I know there are open-source versions out there a plenty, but what fun is that?!) I have a book by Larry Ullman that describes how to do it, but I don't have the book with me and have never programmed such a thing - obviously - so I'm not sure how hard it would be and what you would get for the effort?! Thanks, Debbie Hi, I have a form that I want to allow users to be able to add specific links, some are set types (domains) and just require the iser to enter the link, however, one is for whatever they wish and they must enter a name to describe it. Now im going to enter it into a database with the following columns: USER_ID || LINK_URL || LINK_TYPE || LINK_NAME Link name is optional (only needed if the link type is their own custom one), the link types are ID's related to a table of link types (facebook, twitter etc). Now I'm assuming that to differentiate the form elements for insertion into the database I would need to have a hidden form element with the type ID inside? However I don't really know how to go on from here. A small version of the form would be <input type="text" name="facebook_link" /> <input type="hidden" name="facebook_id value="1" /> <input type="text" name="twitter_link" /> <input type="hidden" name="twitter_id value="2" /> <input type="text" name="own_site" /> <input type="text" name="own_site_description" /> <input type="hidden name="own_site_id" value="3" /> However, I'm assuming this is wrong because I'll need to enter everything into an array won't I? I just can't get my head round it to out put thi results into a foreach statement. Can anybody help me please? 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. Hello,
I recently posted here about an issue I was having with my database orientated products page.
I have now run into another problem where say if, /db.php was typed or /db.php?p=IDoNotExist was typed, it returns blank.
I have in my code the desired content to be displayed, but it just doesn't seem to want to make a show.
I was also wondering if it is possible to show different content for whatever the URL is, so for no parameter, the content about the products, and a non existent one, maybe "Product not found"?
Here is my code:
<?php $db=mysql_connect ("localhost", "webwibco_charlie", "Hello123") or die ('I cannot connect to the database because: ' . mysql_error()); $mydb=mysql_select_db("webwibco_products"); include("header.php"); $status = htmlspecialchars( @$_GET ['p'] ); if ($status == "floorpuzzles") { echo "<h1>Our Floor Puzzles</h1>"; $sql="SELECT ID, Name, Tags, Description, Category FROM products WHERE Category LIKE '%" . FloorPuzzles . "%'"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ $Name =$row['Name']; $ID =$row['ID']; $Description =$row['Description']; echo "<div class=\"box\">"; echo "<h1>$Name</h1>"; echo "<div class=\"floorbox\"><a href=\"?p=$ID\"><img src=\"images/products/catalogue/big/floorpuzzles/$ID.jpg\" class=\"small\"></a></div>"; echo "<h2>$Description</h2>"; echo "</div>"; } ?> <? }else{ if ($status == $_GET["p"]) { $sql="SELECT ID, Name, Tags, Description, Pieces, Size, Barcode, Category FROM products WHERE ID = '" . $_GET['p'] . "'"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ $Name =$row['Name']; $ID =$row['ID']; $Description =$row['Description']; $Pieces =$row['Pieces']; $Size =$row['Size']; $Barcode =$row['Barcode']; echo "<div class=\"1\">"; echo "<h1>$Name</h1>"; echo "<div class=\"bigbox\">"; echo "<div class=\"floorbox\"><img src=\"images/products/catalogue/big/floorpuzzles/$ID.jpg\" class=\"big\"></div>"; echo "</div>"; echo "</div>"; echo "<div class=\"2\">"; echo "<p>Puzzle Pieces: $Pieces</p> <p>Puzzle Size: $Size</p> <p>Barcode: $Barcode</p>"; echo "</div>"; } }else{ ?> <? echo"<h1>Our Products</h1> <p>Our jigsaw puzzles are hand cut by skilled craftsmen and therefore each one is unique with self-correcting pieces. There is a strict quality control process at all stages by our highly experienced staff. The puzzles are durable and provide fun and excitement, enhancing learning and a child’s development.<p> <p>All of our jigsaws are made using materials from sustainable resources grown in managed forests. Where possible we support companies in the UK and source our components locally, most of our suppliers are in the East Midlands, many in Derbyshire and Nottinghamshire. We keep packaging to a minimum and take our environmental and ethical responsibilities very seriously.</p> <p>Reducing waste and recycling was a way of life for us before it became fashionable. We are constantly searching for new ideas and consult teachers when developing our jigsaws, which are often used within the national curriculum.</p> <p>As well as making our own range, we manufacture for leading suppliers to the education market. Check for \"Made in Britain\" and it is probably made by us.</p> <p>We have a wide variety of products available for viewing, from classic floor puzzles to innovative inset trays. You can take a look at all our products on this page, simply use the navigation buttons to your left.</p>"; }} include("footer.php"); ?>The final echo is what I wish to be displayed on the URL without or with an invalid parameter. Here is my site URL: http://www.webwib.co...saws/search.php (note that only the "Floor Puzzles" category has content within it). Thank you in advance for assistance. 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? 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 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. 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? |