PHP - Classes, Interfaces And Methods
Hi, I am trying to get my head around classes, interfaces and methods for different animals
this is what I have so far: <?php interface animal { function walk(); function fly(); function swim(); } class monkey implements animal{ const interface1 = "I am from test class"; function noise() { echo "ooh ooh ah ah!"; } function walk() { echo "monkey is walking"; } function fly() { echo "monkey is Flying"; } function swim() { echo "monkey is Swimming"; } public function display() { echo monkey::interface1; echo PHP_EOL; } } class bear implements animal{ const interface1 = "I am from test class"; function noise() { echo "Grrr!"; } function walk() { echo "Bear is walking"; } function fly() { echo "Bear is Flying"; } function swim() { echo "Bear is Swimming"; } public function display() { echo bear::interface1; echo PHP_EOL; } } $Obj = new monkey(); $Obj->display(); $Obj1 = new bear(); $Obj1->display(); ?> I'm a bit stumped as animal interface not calling all functions?! please help Similar TutorialsWould someone help me out with Abstract Classes and Interfaces... Some questions... 1.) When you have an Interface with Methods, then any Concrete Class that "implements" said Interface must include all of the listed Methods, correct? 2.) When you have an Abstract Class with Properties & Methods, are you required to use all of the listed Properties & Methods similar to how an Interface works? 3.) What is the intent of using Abstract Classes vs. Interfaces? TomTees hello, i have been following the php.net oop manual but im having a little trouble understanding something. on this page in the manual: http://uk3.php.net/manual/en/language.oop5.basic.php it shows this code and if i seperate it out i cant get it to echo the results i want. what am i doing wrong? i have added a little extra code . class Bear Code: [Select] class Bear { // define properties public $name; public $weight; public $age; public $sex; public $colour; // constructor public function __construct() { $this->name = "winny the poo"; $this->weight = 100; $this->age = 0; $this->sex = "male"; $this->colour = "brown"; } // define methods public function eat($units) { echo $this->name." is eating ".$units." units of food... <br/>"; $this->weight += $units; } public function run() { echo $this->name." is running... <br/>"; } public function kill() { echo $this->name." is killing prey... <br/>"; } public function sleep() { echo $this->name." is sleeping... <br/>"; } } class PolarBear Code: [Select] class PolarBear extends Bear { // constructor public function __construct() { parent::__construct(); $this->colour = "white"; $this->weight = 600; } function polarbar() { // Note: the next line will issue a warning if E_STRICT is enabled. Bear::bear(); } // define methods public function swim() { echo $this->name." is swimming... "; } } now if i try to get back the results i have trouble. this is fine Code: [Select] $bear = new Bear(); $bear->eat($units); $bear->eat(); $bear->run(); $bear->kill(); $bear->sleep(); that echos back Quote //THE BEAR winny the poo is eating 5 units of food... winny the poo is eating units of food... winny the poo is running... winny the poo is killing prey... winny the poo is sleeping... //THE POLAR BEAR winny the poo is eating 5 units of food... winny the poo is eating units of food... winny the poo is running... winny the poo is killing prey... winny the poo is sleeping... winny the poo is swimming... THAT FINE but how come i can echo out each of the properties? why do these ways not work? Code: [Select] Bear::eat($units); Bear::eat(); Bear::run(); Bear::kill(); Bear::sleep(); or Code: [Select] $bear = new Bear(); $bear->$name; $bear->$weight; $bear->$age; $bear->$sex; $bear->$colour; or Code: [Select] echo Bear::eat($units); echo Bear::eat(); echo Bear::run(); echo Bear::kill(); echo Bear::sleep(); or Code: [Select] $bear = new Bear(); echo $bear->$name; echo $bear->$weight; echo $bear->$age; echo $bear->$sex; echo $bear->$colour; and the same goes for PolarBear if i try and get back any of the properties on a page i get nothing ??? i even tried putting it in a loop and that didnt work Code: [Select] $bear = new Bear(); foreach ($bear as $bears){ echo $bears->$name; echo $bears->$weight; echo $bears->$age; echo $bears->$sex; echo $bears->$colour; } whats wrong. why cant i get any results from these ? thanks So, I'm starting a new project and thought I would try a new approach at loading files and classes to process output. I think my logic is correct, but for some reason I'm getting a blank page. Basically instead of having seperate pages to output different functions and such, I store everything in one page. It's the same deal as the switch case approach, but it uses a foreach loop to cycle through the actions, classes, and functions which are stored in an array. Here's my index.php file: Code: [Select] <?php require('config.php'); include('languages/english.php'); include('classes/Template.php'); $template = new Template; $viewPages = array( 'category' => array('classfile' => 'Category.php', 'classname' => 'category', 'functions' => array('create', 'delete', 'modify', 'merge')), 'questions' => array('classfile' => 'Question.php', 'classname' => 'Question', 'functions' => array('create', 'delete', 'modify', 'votegood', 'votebad')) ); $currentPage = $_REQUEST['action']; foreach($viewPages as $action => $settings){ if($currentPage == $action){ require(INCLUDE_ROOT.'/classes/'.$settings['classfile']); $class = new $settings['classname']; $function = $_REQUEST['do']; $class->$function(); $template->loadTemplate($settings['classname']->viewFile, $vars = array()); if($template->message == FALSE){ die($template->message); } } } ?> Here's the Template class file: Code: [Select] <?php class Template { var $file; var $vars; var $message; function loadTemplate($file, $vars){ if(empty($file) || empty($vars)){ $this->message = LANG_ERR_7; } else if($file = file_get_contents(INCLUDE_ROOT.'/'.$file)){ $this->message = LANG_ERR_7; } else { foreach($vars as $key => $val) $file = str_replace('{'.$key.'}', $val, $file); } $this->message = FALSE; return $file; } } ?> I tried visiting the category action(index.php?action=category;do=create). This is the classfile for that Code: [Select] <?php class category { var $id; var $title; var $description; var $uri; var $message = array(); var $vars = array(); var $viewFile = ''; function create(){ if($_POST['submit']){ //Review the user input and make ure everything is ok $messages = array(); if($this->title == FALSE){ $messages['title'] = LANG_ERR_1; } else if(strlen($this->title) > 30 || strlen($this->title < 5)){ $messages['title'] = LANG_ERR_2; } else if($this->description == FALSE){ $messages['description'] = LANG_ERR_3; } else if(strlen($this->description) > 400 || strlen($this->description) < 10){ $messages['description'] = LANG_ERR_4; } else { $messages = FALSE; } if($messages != FALSE){ $this->messages = $messages; $this->viewFile = INCLUDE_ROOT.'/template/index_body.tpl'; } else { $this->title = htmlentities($this->title); $this->title = stripslashes($this->title); $this->title = htmlspecialchars($this->title); $this->description = htmlentities($this->description); $this->description = htmlspecialchars($this->description); $this->description = nl2br($this->description); $query = " INSERT INTO categories (c_title, c_desc) VALUES('".$this->title."', '".$this->desscription."')"; if(mysql_query($query)){ $this->message['succes'] = LANG_ERR_5; } else { $this->message['fail'] = LANG_ERR_6; } $this->viewFile = INCLUDE_ROOT.'/template/message_body.tpl'; } } else { $this->viewFile = INCLUDE_ROOT.'/template/create_category.tpl'; } } } ?> Now if you look at the Category class, the template file it sets is the "category_create.tpl" file, which I haven't created yet. I'm expecting there to be an error associated with the template class and the file_get_contents function that calls the file, but like I said, I'm just getting a blank page. I've never tried this approach before, so I have no idea what's causing this. Any help would be greatly appreciated. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=345635.0 Currently I'm learning about objects and classes. I followed a tutorial about making a DB abstraction class (a mySQL select) and then I tried to adapt it and wrote a method to Insert a new name. However, then I had a problem: what if the value already exists in the DB? So I thought maybe I could write a method for that too, and hopefully this would be re-usable for other purposes. So I'm posting the code here and I hope someone could take a look at it, since I do not want to start any bad practices and start a habit of writing sloppy code. Would the code below be considered 'good code'? <?php // This file is called database.php class database { public $mysql; function __construct() { $this->mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Database connection failed'); } /* Function to check whether value: $queriedName already exists inside table: $table and column: $column */ function findMatch($table, $column, $queriedName) { if ($result = $this->mysql->query("SELECT * FROM $table WHERE $column='$queriedName'")) { if (!$numberOfRows=$result->num_rows) { return false; } else { return true; } } } /* Function to select all records from table: $table */ function selectAll($table) { if ($result = $this->mysql->query("SELECT * FROM $table") ) { while($row=$result->fetch_object()) { $nameFields[]=$row->names; } return $nameFields; } } /* Function to insert a name: $newName into table: $table. Uses method finMatch to avoid doubles */ function insertName($table, $newName) { if ($this->findMatch($table, 'names', $newName)) { $result="Person already exists!"; return $result; } else { $result = $this->mysql->query("INSERT INTO $table(names) VALUES ('$newName')"); return $result; } // } } ?> Main page: // This file is called index.php require('database.php'); $newName='Mary Jane'; $result=$myDb->insertname('mytable', $newName); echo $result; I'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. So I have been writing PHP constantly for a few months now, and have a pretty good grasp on OOP coming from other languages. One thing I never really use is interfaces, I get it when a class implements an interface, that class is required to have implemented methods from a interface, or a constant that is required by an interface. Seems like the kinda thing you would need when you are on a large team mainly for naming consistency? Is this something I should be using? I know I can get away with not using it, but should I use it to be up to modern php standards?
Thanks
What is the purpose of using an Interface in OOP? I understand the textbook definition, but am not getting the extra value that they provide... TomTees I am working on a module that receives some info and provides dimensions and weights of products to the caller.
The way I get those is from existing Excel tables used by the company. Some product types have their dimensions only. Some have both dimensions and weights. To clarify - all products have both weight and dimensions but not all are specified on the Excel tables that I am using. so say "Apple" has dimensions on 1 x 1 x 1, but no weight is given. (Weight can be computed separately and in fact there is an existing class that does this already for Pear.). and "Pear" has dimensions 2 x 1 x 1 and weighs 1lbs. In short, some classes have both getWeight() and getDimensions() methods, like Pear(), and some classes just have getDimensions(), like Apple(). I am confused as to which way to go. I can create PearDimensions() class and PearWeight() and separate concepts of "weight" and "dimensions" some more and use a DimensionFactory() and WeightFactory() to instantiate the right object for the circumstances, or I can use "implements" WeightAwaretInterface and HeightAwaretInterface on Apple/Pear classes and leave them as is, thus mixing up the Weight/Dimension getters/causes. So in short I am a tad confused and wondering if there is just a good way to maintain these. Right now I am using DimensionFactory() and WeightFactory() and instantiate Pear class twice (once in each factory) since Pear has both getWeight() and getDimensions() methods. I feel weird creating the same Pear object in both factories. Do you have a recommendation for this, or do I just "hack it" (i.e. leave it as is)? Do interfaces in PHP include default methods, which are available in Java 7 and 8. Default methods allow you to add default functionality in the interface itself. So when a class implements it, it can use the default definition from the interface. This is in contrast to an abstract method which has no method body.
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? 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? I don't know if this belongs here; sorry if it doesn't. I'm using a method=get on a form as I need to pass information through a URL once the form has been submitted. But I also need to INSERT some data from that form to multiple tables. - How can I stop the GET from passing my other variables into the URL? - How do I make the form submit to itself? I need to use the 'index.php?p=checkout' as this matches with a switch statement, which matches to the checkout page. The function PHP_SELF will just refresh to the index.php page, which will not have any of this checkout's page validation. Here's my code: Code: [Select] <h2>Please enter your details</h2> <h3>All fields required</h3> <div id="checkout"> <?php if (isset($_GET['checkout'])){ require_once ('./includes/connectvars.php'); $title = $_GET['title']; $fname = $_GET['fname']; $sname = $_GET['sname']; $ctype = $_GET['ctype']; $cnumber = md5($_GET['cnumber']); $syear = $_GET['smonth'] . $_GET['syear']; $fyear = $_GET['fmonth'] . $_GET['fyear']; $service = $_GET['cardAuth']; $amount = $_REQUEST[$total]; $msg = rand(1000,9999); $api = 'd41d8cd98f00b204e9800998ecf8427e'; $b_house = $_GET['b_house']; $b_postcode = $_GET['b_postcode']; $b_city = $_GET['b_city']; $b_country = $_GET['b_country']; $d_house = $_GET['d_house']; $d_postcode = $_GET['d_postcode']; $d_city = $_GET['d_city']; $d_country = $_GET['d_country']; $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query = "INSERT INTO customer (cust_id, first_name, last_name) VALUES ('', '$fname', '$sname') "; $query = "INSERT INTO bill (cust_id) VALUES ('') "; $query = "INSERT INTO deliver (cust_id) VALUES ('') "; mysqli_query($dbc, $query); } //.'service='.$service.'msg_id='.$msg.'num_md5='.$cnumber.'amount='.$amount.'currency=GBP'.'api_key='.$api. ?> <form method="get" action="index.php?p=checkout"> <table> <tr> <td><input type="hidden" name="cardAuth" /></td> </tr> <tr> <td> Title: </td> <td> <select name="title" value="<?php if (!empty($title)) echo $title; ?>" > <option></option> <option>Mr</option> <option>Sir</option> <option>Ms</option> <option>Miss</option> <option>Mrs</option> </select> </td> </tr> <tr> <td> First Name: </td> <td> <input type="text" name="fname" value="<?php if (!empty($fname)) echo $fname; ?>"/> </td> </tr> <tr> <td> Surname: </td> <td> <input type="text" name="sname" value="<?php if (!empty($sname)) echo $sname; ?>"/> </td> </tr> <tr> <td> </td> </tr> <tr> <td> Card Type: </td> <td> <select name="ctype" value="<?php if (!empty($ctype)) echo $ctype; ?>"> <option>mastercard</option> <option>visa</option> <option>amex</option> <option>solo</option> <option>maestro</option> <option>jcb</option> <option>diners</option> </select> </td> </tr> <tr> <td> Card Number: </td> <td> <input type="text" name="cnumber" value="<?php if (!empty($cnumber)) echo $cnumber; ?>"/> </td> </tr> <tr> <td> Valid From: </td> <td> <select name="smonth" value="<?php if (!empty($smonth)) echo $smonth; ?>"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> <select name="syear" value="<?php if (!empty($syear)) echo $syear; ?>"> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> </select> </td> </tr> <tr> <td> Expires End: </td> <td> <select name="fmonth" value="<?php if (!empty($fmonth)) echo $fmonth; ?>"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> <select name="fyear" value="<?php if (!empty($fyear)) echo $fyear; ?>"> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> </select> </td> </tr> <tr> <td><h4>Billing Address</h4></td> </tr> <tr> <td> House Name/ Number: </td> <td> <input type="text" name="b_house" /> </td> </tr> <tr> <td> Postcode </td> <td> <input type="text" name="b_postcode" /> </td> </tr> <tr> <td> City: </td> <td> <input type="text" name="b_city" /> </td> </tr> <tr> <td> Country: </td> <td> <input type="text" name="b_country" /> </td> </tr> <tr> <td><h4>Delivery Address</h4></td> </tr> <tr> <td> House Name/ Number: </td> <td> <input type="text" name="d_house" /> </td> </tr> <tr> <td> Postcode </td> <td> <input type="text" name="d_postcode" /> </td> </tr> <tr> <td> City: </td> <td> <input type="text" name="d_city" /> </td> </tr> <tr> <td> Country: </td> <td> <input type="text" name="d_country" /> </td> </tr> <tr> <td> </td> </tr> <tr> <td> </td> <td> <input type="submit" name="checkout" value="Checkout"/> </td> </tr> </table> </form> </div> hey guys im wdondering if there's a magic method which works like
__GET()but allows you to put a parameter in...thank you <?php class test { public function run() { $this->object->('string'); // __get with parameter? } public function __get($value) { return $this->{$value} } } ?> what are magic methods? when do we need to use magic methods? what are the advantages of using magic methods? thanks in advanced. I can't find an explicit answer on this anywhere, but when you create a child class from an abstract class must you use ALL of the methods that are inside the abstract class in the new child class? Or are these methods just available to the child class to pick and choose?
I have two classes were one extends the other but they both have magic methods __get __call and __set but when trying to call a magic method it conflicts one with the other as you can imagaine...is there a way of getting around this ie. name spaces
or do I simply have to rewrite my classes
thank you
Hi PhpFreaks, I have a method that I need to be initialised dynamically and I am not sure if the code below will work I have been able to workout if the method exists but I have not found a way to it get to return the array. Has anyone go any ideas? The error I get is: Catchable fatal error: Object of class Forms could not be converted to string Code: [Select] public function setMethodForms($methodName){ echo $methodName." and does it exist ". (int)method_exists($this->formsObj, $methodName); //test to see if the method exists if ((int)method_exists($this->formsObj, $methodName) == 1){ //if it does execute //print_r ($this->formsObj->projects()); //test to see if object works $return call_user_func($this->formsObj."->".$methodName."()"); } return $return; } Is there any way to produce a custom magic method? Let's say when I try to get an attribute that doesn't have any value, a method gets called that gives that attribute a value. So I want a method to be triggered when I try to get a value from an attribute that doesn't have any value. In javascript you can do multiple methods on the same line like: if(document.getElementById('myElement').className.match(/^[0-9]/)){/*Do something*/} in that we have getElementById() and match() on the same line, and it works the same as if you were to split them on multiple lines. Is it possible to do that with php? For example: $obj = new MyObject(); $obj->add(2, 3)->to_string(); |