I have one file user.php with constructor for the client:
class Client{
public $name;
public $pin;
public $balance;
function __construct($name, $pin, $balance){
$this->name = $name;
$this->pin = $pin;
$this->balance = $balance;
}
}
$client1 = new Client("Alan", "0201", 2000);
?>
Also I have a file where i do some math to the client object:
$balance = $client1->balance;
function withdrow($amount, $balance){
$currentBalance = $balance - $amount;
if($balance < $amount){
echo "You are low on balance";
}
else{
$client1->balance = $currentBalance;
return $currentBalance;
}
}
And 3rd html file where I include First file with the client and I want to echo the updated value of balance on the screen.But its print the value set in client.How to update the balance.
My code look like this right now but setter not change the value balance:
class Client{
public $name;
private $pin;
private $balance;
function __construct($name, $pin, $balance){
$this->name = $name;
$this->pin = $pin;
$this->balance = $balance;
}
private function setPin($pin){
$this->pin = $pin;
}
public function getPin(){
return $this->pin;
}
public function setBalance($balance){
$this->balance = $balance;
}
public function getBalance(){
return $this->balance;
}
}
$client1 = new Client("Alan", "0201", 2000);
you must call function with call by reference
function withdrow($amount, &$balance){ /** call by reference */
$currentBalance = $balance - $amount;
if($balance < $amount){
echo "You are low on balance";
}
else{
$client1->balance = $currentBalance;
return $currentBalance;
}
}
Related
I have my code here and I dont know how to delete object with this kind of method
$patient->deletePatient(2) im a beginner and I cant find an answer in internet and I think the way i use var_dump was incorrect please help im stuck
this is my code:
<?php
$index = 0;
class Clinic {
public $name;
public $age;
public $gender;
function Patient($name,$age,$gender){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$id = $name;
$id = $age;
$id = $gender;
}
function assignPatient($name,$age,$gender){
$this->Patient($name,$age,$gender);
}
function deletePatient($id=0){
$this->Patient($id);
var_dump((unset) $id);
}
}
$patient = new Clinic;
$patient->assignPatient("Patrick star",18,"Male");
$patients[$index] = $patient;
$index++;
$patient->assignPatient("SpongeBob Squarepants",17,"Male");
$patients[$index] = $patient;
$index++;
$patient->assignPatient("Eugene Krab",28,"Male");
$patients[$index] = $patient;
$index++;
$patient->deletePatient(2);
foreach($patients as $patient)
{
echo $patient->name . " ";
echo $patient->age . " ";
echo $patient->gender . "\n";
}
Patient and Clinic should be separate objects. Then you can store Patient objects inside Clinic->patients array.
class Patient{
private $name;
private $age;
private $gender;
public function __construct($name, $age, $gender){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
public function getName(){
return $this->name;
}
public function getAge(){
return $this->age;
}
public function getGender(){
return $this->gender;
}
}
class Clinic{
private $patients = [];
public function getPatients(){
return $this->patients;
}
public function assignPatient($name, $age, $gender){
$this->patients[] = new Patient($name, $age, $gender);
}
public function deletePatient($index){
unset($this->patients[$index]);
}
}
$clinic = new Clinic();
$clinic->assignPatient("Patrick star",18,"Male");
$clinic->assignPatient("SpongeBob Squarepants",17,"Male");
$clinic->assignPatient("Eugene Krab",28,"Male");
$clinic->deletePatient(1);
var_dump($clinic->getPatients());
<?php
class Patient {
public $name;
public $age;
public $gender;
function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
class Clinic {
private $patients = [];
private $patientIndex = 0;
function assignPatient($patient) {
$this->patients[$this->patientIndex] = $patient;
++$this->patientIndex;
return $this->patientIndex;
}
function deletePatient($id) {
if(array_key_exists($id, $this->patients)) {
unset($this->patients[$id]);
return true;
}
return false;
}
function getPatients() {
return $this->patients;
}
}
$clinic = new Clinic();
$patient1 = new Patient("Patrick star",18,"Male");
$id1 = $clinic->assignPatient($patient1);
$patient2 = new Patient("SpongeBob Squarepants",17,"Male");
$id2 = $clinic->assignPatient($patient2);
$patient3 = new Patient("Eugene Krab",28,"Male");
$id3 = $clinic->assignPatient($patient3);
$clinic->deletePatient($id2);
foreach($clinic->getPatients() as $patient) {
var_dump($patient);
}
I want to pass function values to another function in the same class, like to store some values in a variable and then call this variable in another function in the same class.
Here is my Code
public function ven_coupon()
{
if ($_POST) {
$number = $_POST['coupon'];
$query = $this->front->ven_coupon($number);
if (count($query) <= 0 ) {
echo "Not Valid";
}
$payment = $this->cart->total();
$dis = $query['discount'];
$name = $query['username'];
$number = $query['number'];
$discount['discount'] = ($payment*$dis)/100;
$discount['data'] = $dis;
$this->load->view('checkout',$discount);
}
}
public function addcart()
{
$ven = $this->ven_coupon();
echo $ven($name);
echo $ven($dis);
echo $ven($number);
}
You could create the fields(variables) you need outside the function then use them using the this keyword. For example:
private $dis;
private $name;
private $number;
public function ven_coupon()
{
if ($_POST) {
$number = $_POST['coupon'];
$query = $this->front->ven_coupon($number);
if (count($query) <= 0 ) {
echo "Not Valid";
}
$payment = $this->cart->total();
$this->dis = $query['discount'];
$this->name = $query['username'];
$this->number = $query['number'];
$discount['discount'] = ($payment*$dis)/100;
$discount['data'] = $dis;
$this->load->view('checkout',$discount);
}
}
public function addcart()
{
$ven = $this->ven_coupon();
echo $this->name;
echo $this->dis;
echo $this->number;
}
Scope of variable is inside the function. You need to made variable as a part of class as:
Basic Example:
class yourClass{
private $name;
public function functionA(){
$this->name = "devpro"; // set property
}
public function functionB(){
self::functionA();
echo $this->name; // call property
}
}
your function ven_coupon() doesn't return anything, therefore $ven is empty when you read it in your function addcart().
in order to pass several variables from one function to another, you need to create an array.
function ven_coupon(){
$dis = $query['discount'];
$name = $query['username'];
$data=array('dis'=>$dis,'name'=>$name)
return $data
}
function addcart()
{
$ven = $this->ven_coupon();
echo $ven['name'];
//etc.
}
Edit: as you are already using an array $query you could simply return $query; in function ven_coupon and then read it in your function addcart()
I want have an in-memory data structure to be able to add or remove an item (in this instance a student) into some sort of table (just like a shopping cart) from the collection class I have created. At the moment, it just displays students. For instance, if I click add student, it will pop up below, and I can delete this student from below also.
How I could implement this?
Here is my Member.php class
<?php
class Member {
private $name;
private $age;
private $gender;
private $course;
public function __construct($name,$age, $gender, $course){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$this->course = $course;
}
public function setName($name) { //Sets the age value
$this->name = $name;
}
public function setAge($age) { //Sets the age value
$this->age = $age;
}
public function setGender($gender) { //Sets the gender value
$this->gender = $gender;
}
public function setCourse ($course) {
$this->course = $course;
}
public function getName() { //Gets the name value
return $this->name;
}
public function getAge() { //Gets the age value
return $this->age;
}
public function getGender() { //Gets the gender value
return $this->gender;
}
public function getCourse() {
return $this->course;
}
}
?>
Here is my ObjectCollection.php
<?php
class ObjectCollection
{
//This is an array to hold line items
private $items_array ;
private $itemCounter; //Count the number of items
public function __construct() {
//Create an array object to hold line items
$this->items_array = array();
$this->itemCounter=0;
}
public function getItemCount(){
return $this->itemCounter;
}
public function addItem($item) {
$this->itemCounter++;
$this->items_array[] = $item;
}
public function getItem($index) {
return $this->items_array[$index];
}
}
?>
And finally displaying this through testcollection.php
<?php
$ObjColl = new ObjectCollection();
$member1 = new Member("Jessica Davidson", 21, "Female", "Computing");
$ObjColl->addItem($member1);
$member2 = new Member("Lucy Barnes", 22, "Female", "History");
$ObjColl->addItem($member2);
$member3 = new Member("Mark Smith", 24, "Male", "Social Science");
$ObjColl->addItem($member3);
for($i = 0;$i < $ObjColl->getItemCount();$i++){
$item = $ObjColl->getItem($i);
if ($item instanceof Member) {
print "<br> University Member: ";
}
print "Name: " . $item->getName();
print ". Age: " . $item->getAge();
print ". Gender: " . $item->getGender();
print ". Enrolled on: " .$item->getCourse() . " course<br>";
}
?>
At first if your ObjectCollection must collect only objects of Member class, use parameter type declaration. It’s good practice in OOP.
public function addItem(Member $item)
At second if you want work with ObjectCollection like with array, implement ArrayAccess and Iterator interfaces.
Example
<?php
class Member{
private $__name;
public function __construct($name){
$this->__name = $name;
}
public function getName(){
return $this->__name;
}
}
class MemberCollection implements ArrayAccess, Iterator{
private $__Collection = [];
private $__position = 0;
public function __construct(){
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->__Collection[] = $value;
} else {
$this->__Collection[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->__Collection[$offset]);
}
public function offsetUnset($offset) {
unset($this->__Collection[$offset]);
}
public function offsetGet($offset) {
return isset($this->__Collection[$offset]) ? $this->__Collection[$offset] : null;
}
function rewind() {
$this->__position = 0;
}
function current() {
return $this->__Collection[$this->__position];
}
function key() {
return $this->__position;
}
function next() {
++$this->__position;
}
function valid() {
return isset($this->__Collection[$this->__position]);
}
public function addItem(Member $Member){
$this->offsetSet(null, $Member);
}
}
$MC = new MemberCollection();
$Member1 = new Member('Name 1');
$Member2 = new Member('Name 2');
$MC->addItem($Member1);
$MC->addItem($Member2);
foreach ($MC as $Member){
echo '<br>' . $MC->key() . ':<br>';
var_dump($Member->getName());
}
unset($MC[0]); //Delete member from collection
?>
I've got a Accounts class which looks like this:
class Account {
public $accID;
public $balance;
public function __construct($accNum, $startBalance){
$this->accID = $accNum;
$this->balance = $startBalance;
}
public function deposit($amount){
$this->balance = $balance + $amount;
}
public function withdraw($amount){
if($amount > $this->balance)
die("There is not enough money in this account to withdraw");
$this->balance = $balance + $amount;
}
public function getbalance() {
return $this->balance;
}
public function getaccID() {
return $this->accID;
}
public function setaccID($accID){
$this->accID = $accID;
}
}
This is fine, however I am inputting from a text file which deals with transactions. Example: "105 D 200" which means go to account 105 and Deposit 200.
I have been able to create multiple Accounts and split the transaction file into their different parts.
foreach($getFile as $v) {
list($c, $d, $e) = explode(" ", $v);
$acc[] = $c;
$type[] = $d;
$amount[] = $e;
}
I just cannot figure out how to use these sub strings in order work with my functions in the accounts class.
Any help would be appreciated, thanks you!
First of all , there is a logic error in your withdraw method, you are adding an amount and not subtracting it from the balance,
You can create some kind of Account Manager , which will store all accounts and you can get the account from it,delete,get all accounts ... etc
Then you can read file and process it.
Overall code would be something like this.
foreach($getFile as $v) {
list($c, $d, $e) = explode(' ', $v);
$account = AccountManager::manager()->getAccountWithId($c);
if($d == 'D') {
$account->deposit($e);
}
// add more cases when to withdraw ... etc
}
print_r(AccountManager::manager()->getAccounts());
// This will be a Singleton
class AccountManager {
private static $instance;
private $accounts;
protected function __construct() {
$this->accounts = Array();
}
// To create a single instance
public static function manager() {
if(AccountManager::$manager === null) {
AccountManager::$manager = new AccountManager();
}
return AccountManager::$manager;
}
public getAccountWithId($accountId,$autoCreate = true) {
if(array_key_exists($accountId,$this->accounts)) {
return $this->accounts[$accountId];
} else if($autoCreate) {
// Create a new account with zero balance
$account = new Account($accountId,0);
$this->accounts[$accountId] = $account;
return $account;
}
return null;
}
public deleteAccountWithId($accountId) {
if(array_key_exists($accountId,$this->accounts)) {
unset($this->accounts[$accountId]);
}
}
public getAccounts() {
return array_values($this->accounts);
}
}
class Account {
public $accID;
public $balance;
public function __construct($accNum, $startBalance){
$this->accID = $accNum;
$this->balance = $startBalance;
}
public function deposit($amount){
$this->balance += $amount;
}
public function withdraw($amount){
if($amount > $this->balance) {
die("There is not enough money in this account to withdraw");
}
// Make sure you are substracting the amount and not adding it.
$this->balance -= $amount;
}
public function getbalance() {
return $this->balance;
}
public function getaccID() {
return $this->accID;
}
public function setaccID($accID){
$this->accID = $accID;
}
}
I'm learning OOP, and got a little problem here with not understanding the code.
Here it is.
class ShopProduct {
private $title;
private $producerMainName;
private $producerFirstName;
protected $price;
private $discount = 0;
function __construct( $name, $firstName, $mainName, $price) {
$this->title = $name;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
public function getProducer() {
return "{$this->producerMainName} "."{$this->producerFirstName} \n ";
}
public function setDiscount($num){
$this->discount = $num;
}
public function getDiscount() {
return $this->discount;
}
public function getTitle() {
return $this->title;
}
public function getPrice() {
return ($this->price - $this->discount);
}
public function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}
}
class CDProduct extends ShopProduct {
private $playLength = 0;
public function __construct($title, $firstName, $mainName, $price, $playLength) {
parent::__construct($title, $firstName, $mainName, $price);
$this->playLength = $playLength;
}
public function getPlayLength() {
return $this->playLength;
}
public function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": {$this->playLength()} minutes";
return $base;
}
}
class BookProduct extends ShopProduct {
private $numPages = 0;
public function __construct($title, $firstName, $mainName, $price, $numPages) {
parent::__construct($title, $firstName, $mainName, $price);
$this->numPages = $numPages;
}
public function getNumberOfPages() {
return $this->numPages;
}
public function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": {$this->numPages()} pages";
return $base;
}
}
class ShopProductWriter {
private $products = array();
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
public function write($shopProduct) {
foreach($this->products as $shopProducts){
$str = "{$shopProduct->getTitle()}: "."{$shopProduct->getProducer()}"." {$shopProduct->getPrice()}$ \n";
}
print $str;
}
}
$product = new CDProduct('Song is the rythm','Zyxel','Beatz',50, 60.33);
$write = new ShopProductWriter();
$write->addProduct($product);
$write->write($product);
The problem is here
class ShopProductWriter {
private $products = array();
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
public function write($shopProduct) {
foreach($this->products as $shopProducts){
$str = "{$shopProduct->getTitle()}: "."{$shopProduct->getProducer()}"." {$shopProduct->getPrice()}$ \n";
}
print $str;
}
}
As you see there is condition - if the object is not ShopProduct type - goes error.
But as you see i'm creating CDProduct object.
$product = new CDProduct('Song is the rythm','Zyxel','Beatz',50, 60.33);
$write = new ShopProductWriter();
$write->addProduct($product);
$write->write($product);
It should show error. Anybody can say me what i'm doing wrong?
Objects of CDProduct are also of type ShopProduct. In the class definition:
class CDProduct extends ShopProduct {
So it is an object of both types.
http://php.net/manual/en/language.oop5.inheritance.php
If an object extends a parent or implements an interface, it can be considered of that type also.
http://php.net/manual/en/language.operators.type.php
You got already feedback about why a CDProduct is a ShopProduct, so I just add another hint on some code you've written where PHP has already support for:
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
Instead of doing the check on your own, you can just make use of Type Hinting to reduce your code and make it more expressive:
public function addProduct(ShopProduct $shopProduct) {
$this->products[] = $shopProduct;
}
I hope this helps as you wrote you're currently learning about OOP.