php7 object collection + properties - php

How can I create an object in php (like c#)
for exemple user with 3 properties
class Users
{
private $name;
private $age;
private $sex;
public function __construct($name, $age, $sex) {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
}
how can I add users in the collection
and then loop users collection to get
$user->name
$user->age
$user->sex
thank you

From you given example, it might be achieved like that:
class User
{
const
SEX_M = 1,
SEX_F = 2
;
private
$name,
$age,
$sex
;
public function __construct($name, $age, $sex) {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public function dump()
{
echo "name: $this->name, age: $this->age, sex: "
. ($this->sex === User::SEX_M ? 'm' : 'f') . "<br>\n";
}
}
$collection = array();
$collection[] = new User('Tom' , 10, User::SEX_M);
$collection[] = new User('Jerry', 11, User::SEX_F);
foreach ($collection as $user)
$user->dump();

Related

how to delete object in a constructor in PHP?

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);
}

How to pass array to a class in php?

class User{
public $name ;
public $age ;
public $height ;
public $weight ;
function __construct($name,$age,$height,$weight){
$this->age = $age;
$this->name = $name;
$this->height = $height;
$this->weight = $weight;
}
public function ispis(){
echo $this->age;
}
}
$question_array = [new User ("Ivan","22","174","68"), new
User("Luka","23","174","68") ];
$daniel = new User($question_array);
//$daniel = new User("ivan","22");
$daniel->ispis();
So when i call this function ispis() it doesn't do anything but when i echo inside function __constructor it shows correct values of everything entered. Also when i comment first three lines above //$daniel = new User("ivan","22"); line and uncomment this, ispis() works just fine. Would be nice if someone could explain to me why this is happening. Tnx in advance :)
By the looks of your code you're trying to pass two new User instances into a new user ("daniel").
So basically User is expecting 4 arguments (age, name, height, weight). You've created Luka and Ivan correctly, but you're passing those two Users as arguments when trying to create Daniel. You're giving it Luka and Ivan when it wants age, name, height and weight.
If you simply want to pass an array to the constructor, just pass it as an argument on the new instance:
<?php
class User {
public $name;
public $age;
public $height;
public $weight;
function __construct($args){
$this->age = $args['age'];
$this->name = $args['name'];
$this->height = $args['height'];
$this->weight = $args['weight'];
}
function getAge() {
return $this->age;
}
}
$question_array = [
'name' => 'Daniel',
'age' => '22',
'weight' => '174',
'height' => '68'
];
$daniel = new User($question_array);
echo $daniel->getAge(); // 22
?>
Your question appears a little ambiguous, but perhaps you want to create an object from an array of arguments.
<?php
class User {
public $name;
public $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
public function echoAge()
{
echo $this->age;
}
}
$args = ['Leonard', 21];
$bones = new User(...$args);
$bones->echoAge();
Output:
21
Robert just answered, and his method is one that i use in a personal MVC to define construct or in another way there is also this method that i use always in my MVC :P...
Btw i think Ivan you are doing some confusion with classes...
class User{
public $name ;
public $age;
public $height ;
public $weight ;
function __construct($array){
if (is_array($array)){
foreach($array as $k=>$v){
$this->$k = $v;
}
}
}
public function ispis(){
print 'NAME :' .$this->name .' AGE : ' .$this->age.' HEIGHT : ' .$this->height .' WEIGHT : ' .$this->weight.'<br>';
}
}
$arrayOne = ['name'=>"Ivan",'age'=>"22",'height'=>"174",'weight'=>"68"];
$arrayTwo = ['name'=>"Luke",'age'=>"23",'height'=>"174",'weight'=>"68"];
$ivan = new User($arrayOne);
$luka = new User($arrayTwo);
$ivan->ispis();
$luka->ispis();

Overloading a function in multilevel inheritence in PHP that doesn't take any arguments

I'm learning PHP, just started with the intermediate level. Below is the class hierarchy -
FamilyTree
|
|
Grandparents
|
|
Parents
Parents have an extra property called $dob the rest are inherited from Grandparents
I was able to overload set_values() because they differed in the number of arguments, how do I overload display_values() since it doesn't take any argument?
This is the code :
<?php
class FamilyTree {
protected $name;
protected $sex;
protected $married;
protected $number_of_kids;
public function display_values() {
echo $this->name . "<br />";
echo $this->sex . "<br />";
echo $this->married . "<br />";
echo $this->number_of_kids . "<br />";
}
}
class Grandparents extends FamilyTree {
public function set_values($name, $sex, $married, $number_of_kids) {
$this->name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
}
}
class Parents extends Grandparents {
private $dob;
public function __call($function_name, $arguments) {
if($function_name == 'set_values' && count($arguments) == 5) {
$this->$name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
$this->dob = $dob;
}
}
}
$gp = new Grandparents();
$gp->set_values("James", "Male", 'yes', 5);
$p = new Parents();
$p->set_values("Samuel", "Male", 'yes', 2, '2/5/1974');
$gp->display_values();
Sorry to disappoint you, but you were unsuccessful in "overloading" that method.
If you take a closer look at your implementation if __call:
public function __call($function_name, $arguments) {
if($function_name == 'set_values' && count($arguments) == 5) {
$this->$name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
$this->dob = $dob;
}
}
you will notice that
$this->$name should be $this->name
$name, $sex, $married, $number_of_kids and $dob are all undefined, and should instead be $arguments[0] to $arguments[4].
But your __call implementation doesn't get called at all, because PHP simply discards too many arguments to user-defined functions.
What you can do instead, is override the function and call the parent implementation with parent:::
public function set_values($name, $sex, $married, $number_of_kids, $dob = '') {
parent::set_values($name, $sex, $married, $number_of_kids);
$this->dob = $dob;
}
I'm just initialising $dob to an empty string because it would default to NULL otherwise.
As a side note, if you want to offer a new implementation that takes less arguments than the original one, you can also do that with default arguments:
public function set_values($name, $sex, $married, $number_of_kids = 0) {
parent::set_values($name, $sex, $married, $number_of_kids);
}
which could then be called with either 3 or 4 arguments.
For more complex combinations, declare your new implementation with a default argument for every parameter (in order to make it compatible with the parent implementation) and use func_get_args to handle or redirect the call.
Overriding display_values is simple though, since the number of arguments is just the same:
public function display_values() {
parent::display_values();
echo $this->dob . "<br />";
}
So in full, your code would look like this:
<?php
class FamilyTree {
protected $name;
protected $sex;
protected $married;
protected $number_of_kids;
public function display_values() {
echo $this->name . "<br />";
echo $this->sex . "<br />";
echo $this->married . "<br />";
echo $this->number_of_kids . "<br />";
}
}
class Grandparents extends FamilyTree {
public function set_values($name, $sex, $married, $number_of_kids) {
$this->name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
}
}
class Parents extends Grandparents {
private $dob;
public function set_values($name, $sex, $married, $number_of_kids, $dob = '') {
parent::set_values($name, $sex, $married, $number_of_kids);
$this->dob = $dob;
}
public function display_values() {
parent::display_values();
echo $this->dob . "<br />";
}
}
$gp = new Grandparents();
$gp->set_values("James", "Male", 'yes', 5);
$p = new Parents();
$p->set_values("Samuel", "Male", 'yes', 2, '2/5/1974');
$gp->display_values();
$p->display_values();
For method overloading signature and method name should have to be same. Without these two it would not considered as method overloading. In this case , is is not overloading , but a separate method. You can simply overload by this display_values($name, $sex, $married, $number_of_kids) and set all values
Unless I have misunderstood you, in this instance you are not overrloading set_values via __call in class parent. To overload, the method must be inaccessible.
class Parents extends Grandparents {
private $dob;
public function __call($function_name, $arguments) {
echo 'called';
if($function_name == 'set_values' && count($arguments) == 5) {
$this->$name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
$this->dob = $dob;
}
}
}
This will not print 'called' for $p->set_values("Samuel", "Male", 'yes', 2, '2/5/1974');.
To override the method the parent method must be inaccessible, it doesn't matter about the number of arguments, see this example:
<?php
class FamilyTree {
protected $name;
protected $sex;
protected $married;
protected $number_of_kids;
private function display_values() {
echo $this->name . "<br />";
echo $this->sex . "<br />";
echo $this->married . "<br />";
echo $this->number_of_kids . "<br />";
}
}
class Grandparents extends FamilyTree {
private function set_values($name, $sex, $married, $number_of_kids) {
$this->name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
}
private function drawMe($a)
{}
}
class Parents extends Grandparents {
private $dob;
public function __call($function_name, $arguments) {
echo 'Args: ' . count($arguments);
echo ' | Function name: ' . $function_name;
if($function_name == 'set_values' && count($arguments) == 5) {
$this->$name = $name;
$this->sex = $sex;
$this->married = $married;
$this->number_of_kids = $number_of_kids;
$this->dob = $dob;
}
}
}
$p = new Parents();
$p->display_values();
echo '<br><br>';
$p->set_values("Samuel", "Male", 'yes', 2, '2/5/1974');
This prints:
Args: 0 | Function name: display_values
Args: 5 | Function name: set_values

Managing collection of items through adding/removing

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
?>

return class properties as JSON

I'm trying to encode some properties in a class in php to JSON but all my method is returning is {}
Here's my code, where am I going wrong?
Thanks.
<?php
class Person
{
private $_photo;
private $_name;
private $_email;
public function __construct($photo, $name, $email)
{
$this->_photo = $photo;
$this->_name = $name;
$this->_email = $email;
}
public function getJsonData() {
$json = new stdClass;
foreach (get_object_vars($this) as $name => $value) {
$this->$name = $value;
}
return json_encode($json);
}
}
$person1 = new Person("mypicture.jpg", "john doe", "doeman#gmail.com");
print_r( $person1->getJsonData() );
That's is because you are not using the $json variable but instead you are using $this->$name. Which $this are you refering too? You aren't using the $json variable from what I am seeing.
class Person
{
private $_photo;
private $_name;
private $_email;
public function __construct($photo, $name, $email)
{
$this->_photo = $photo;
$this->_name = $name;
$this->_email = $email;
}
public function getJsonData() {
//I'd make this an array
//$json = new stdClass;
$json = array();
foreach (get_object_vars($this) as $name => $value) {
//Here is my change
//$this->$name = $value;
$json[$name] = $value
}
return json_encode($json);
}
}
$person1 = new Person("mypicture.jpg", "john doe", "doeman#gmail.com");
print_r( $person1->getJsonData() );
Hope it solves you problem. That's how I would do it.
Implement the JsonSerializable interface in your class, starting with PHP 5.4.

Categories