How to pass array to a class in php? - 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();

Related

How can I return multiple values from a function separately?

The issue is quite simple. I need to return multiple values from a function. How can I do it?
Code is below:
<?php
abstract class Products
{
protected $name;
protected $price;
public function __construct($name, $price)
{
$this->name = $name;
$this->price = $price;
}
public function getName()
{
return $this->name;
}
public function getPrice()
{
return $this->price;
}
}
// A new class extension
class Furniture extends Products
{
protected $width;
protected $height;
protected $length;
public function getSize()
{
// return $this->width;
// return $this->height;
// return $this->length;
// return array($this->width, $this->height, $this->length);
}
}
So as far as I understand, when I return something, it will stop the function, so I understand why I can't just do return three times. An attempt to return an array didn't work. It resulted in an error:
Notice: Array to string conversion
How can I return all three of those?
If you change your function to return an array like so:
class Furniture extends Products
{
protected $width;
protected $height;
protected $length;
public function getSize()
{
return [
'width' => $this->width,
'height' => $this->height,
'length' => $this->length
];
}
}
You can then access your data like so:
$furniture = new Furniture;
$size = $furniture->getSize();
$height = $size['height'];
Returning multiple data values by an array is a pretty common thing. Another method would be to use a stdClass, which would pretty much have the same outcome in this case.

how to create default value for for an object? PHP

let's say I have a Human class which has the variable of $gender which doesn't have any value assigned into it. Human has a constructor with the parameter of age, gender, height and weight.
I have another class called Female which inheritance from Human but now the Female class is overriding the $gender variable with a string of Female.
When I create the object let's say $f = new Female(12, 'female', 123, 40);
How can I skip typing the female when creating the object?
I thought we need to create another new constructor in Female class which I did and in the Female class constructor's parameter I have age, gender = 'female', height and weight but this doesn't seem to work.
I tried leaving the gender part empty when creating the object or tried entering empty string such as "".
Can someone give me a hand please? Thanks a lot.
Code for my human class
class Human {
protected $age = 0;
protected $gender;
protected $height_in_cm;
protected $weight_in_kg;
function __construct($age, $gender, $heightCM, $weightKG)
{
$this->age = $age;
$this->gender = $gender;
$this->height_in_cm = $heightCM;
$this->weight_in_kg = $weightKG;
}
/**
* #return int
*/
public function getAge()
{
return $this->age;
}
/**
* #return string
*/
public function getGender()
{
return $this->gender;
}
}
Code for Female class
require_once('Human.php');
class Female extends Human{
protected $gender = 'female';
function __construct($age, $gender = 'female', $heightCM, $weightKG)
{
$this->age = $age;
$this->gender = $gender;
$this->height_in_cm = $heightCM;
$this->weight_in_kg = $weightKG;
}
}
$f = new Female(12,'female',123,40);
echo "Your gender is ". $f->getGender()."<br>";
Simply override the constructor:
class Human {
public function __construct($age, $gender, $height, $weight) {
}
}
class Female extends Human {
public function __construct($age, $height, $weight) {
parent::__construct($age, 'Female', $height, $weight);
}
}
You can just set the value in the extended class:
// If it should be possible to instantiate the Human
// class then remove the "abstract" thing at set the
// "gender" property in the constructer
abstract class Human {
protected $gender;
protected $age;
public function __construct($age) {
$this->age = $age;
}
}
class Female extends Human {
protected $gender = "Female";
}
class Male extends Human {
protected $gender = "Male";
}
Although this works, it really does not make that much sense. The class itself tells you what gender the human is, so you can just call $human instanceof Female.
$person = new Female(18);
if ($person instanceof Female) {
echo "Person is female";
}
You can simply overwrite the constructor:
abstract class Human
{
protected $age;
protected $gender;
protected $height;
protected $weight;
public function __construct($age, $gender, $height, $weight)
{
$this->age = $age;
$this->gender = $gender;
$this->height = $height;
$this->weight = $weight;
}
public function getGender()
{
return $this->gender;
}
}
class Female extends Human
{
public function __construct($age, $height, $weight)
{
parent::__construct($age, 'female', $height, $weight);
}
}
$female = new Female(12, 170, 60);
echo $female->getGender();
I think, in you constructor
__construct($var, $gender="female", $var, $var){
//rest assignment
}
should do it
alternatively, use 3 param constructor with female already set

get member value from object inside array in php

Can't seem to find the answer for this question: how to get a specific value (member value) from an array of objects?
My code is very simple:
$people = array();
class Person {
public $id;
public $name;
public $family_name;
public $dob;
public $image;
public function __construct($id, $name, $family_name, $dob, $image){
$this->$id = (string) $id;
$this->$name = (string) $name;
$this->$family_name = (string) $family_name;
$this->$dob = (string) $dob;
$this->$image = (string) $image;
}
public function get_id(){
return $this->id;
}
}
for ($i=0;$i<$no_clients;$i++)
{
array_push($people, new Person($_SESSION['user_clients'][$i]['client_id'], $_SESSION['user_clients'][$i]['client_name'], $_SESSION['user_clients'][$i]['client_family_name'], $_SESSION['user_clients'][$i]['client_dob'], ROOT_URL.$_SESSION['user_clients'][$i]['client_img']));
}
now I would like to get the id of one of the person from within the people array
$error = $people[$i]->get_id(); //doesn't seem to work
//not getting a value back even though the session variable is correct
as you've probably seen, I'm a PHP newbie so any advice would be great.
Thanks
Your constructor is wrong (no $ sign in front of the properties)
$people = array();
class Person {
public $id;
public $name;
public $family_name;
public $dob;
public $image;
public function __construct($id, $name, $family_name, $dob, $image){
$this->id = (string) $id;
$this->name = (string) $name;
$this->family_name = (string) $family_name;
$this->dob = (string) $dob;
$this->image = (string) $image;
}
public function get_id(){
return $this->id;
}
}
for ($i=0;$i<$no_clients;$i++)
{
$p=new Person($_SESSION['user_clients'][$i]['client_id'], $_SESSION['user_clients'][$i]['client_name'],
$_SESSION['user_clients'][$i]['client_family_name'],
$_SESSION['user_clients'][$i]['client_dob'],
ROOT_URL.$_SESSION['user_clients'][$i]['client_img']);
//print_r($p); //--> check your object
array_push($people, $p);
}
//print_r($people);
Array ( [0] => Person Object ( [id] => 1 [name] => M [family_name] => C [dob] => 2011-07-21 [image] => image/1_margaret.jpg ) )
EDIT:
Reset that $i counter as probably it's last value was 1. Even better use a foreach loop:
foreach ($people as $person){
echo $person->get_id();
}
Your constructor code is not correct, you're incorrectly referencing your properties. Remove the $ from the start of the property names.
Eg change
$this->$id = $id
to
$this->id = $id

get value of private var in a class through typehinted object to assign it in php 5.3

I have been reading Rafactoring by Martin Fowler and in the beginning of the book he uses an example application (written in Java), which I am trying to convert over to PHP for training purposes. (I have trimmed the code down to make this question, but it works if the variables are public.)
The trouble is to create a statement I need access to a value (see switch) using method getCode() of Movie class since $code is private. (Of course if all of the variables were public the code below would work, but I want to keep them private.)
Can someone please shed some light on how I would access the private variable calling the getCode() method of Movie from the switch in statement(). (Or if there is a better way to do it, let me know.)
class Movie {
private $title;
private $code;
public function __construct($title, $code) {
$this->title = $title;
$this->code = $code;
}
public function getCode() {
return $this->code;
}
public function getTitle() {
return $this->title;
}
}
class Rental {
private $movie; // will carry a Movie object
private $days;
public function __construct(Movie $movie, $days) {
$this->movie = $movie;
$this->days = $days;
}
public function getMovie() {
return $this->movie;
}
}
class Customer {
private $name;
private $rentals; // will be a collection of Rental Objects
public function __construct($name) {
$this->name = $name;
}
public function addRental(Rental $rental) {
$this->rentals[] = $rental;
}
public function statement() {
$thisAmount = 0;
foreach ($this->rentals as $each) {
// what is the better way to call this value??????
switch ($each->movie->code) {
case 1:
$thisAmount+= ($each->days - 2) * 1.5;
break;
case 2:
$thisAmount += $each->days * 3;
break;
case 3:
$thisAmount += 1.5;
break;
}
// show figures for this rental
$result = "\t" . $each->movie->title . "\t" . $thisAmount . "\n";
}
return $result;
}
}
// pick a movie
$movie = new Movie('Star Wars', 0);
// now rent it
$rental = new Rental($movie, '2');
// now get statement
$customer = new Customer('Joe');
$customer->addRental($rental);
echo $customer->statement();
You are iterating over a collection of movie in your foreach. So you can do it this way:
foreach($this->rentals as $rental) {
switch($rental->getMovie()->getCode()) {
Of course, you can leave your variable named each. I just find $movie more readable and understandable in this context.
replace your line with just:
$each->getMovie->getCode()

Why is there a constructor method if you can assign the values to variables?

I'm just learning PHP, and I'm confused about what the purpose of the __construct() method?
If I can do this:
class Bear {
// define properties
public $name = 'Bill';
public $weight = 200;
// define methods
public function eat($units) {
echo $this->name." is eating ".$units." units of food... <br />";
$this->weight += $units;
}
}
Then why do it with a constructor instead? :
class Bear {
// define properties
public $name;
public $weight;
public function __construct(){
$this->name = 'Bill';
$this->weight = 200;
}
// define methods
public function eat($units) {
echo $this->name." is eating ".$units." units of food... <br />";
$this->weight += $units;
}
}
Because constructors can do more complicated logic than what you can do in variable initialization. For example:
class Bear {
private $weight;
private $colour;
public __construct($weight, $colour = 'brown') {
if ($weight < 100) {
throw new Exception("Weight $weight less than 100");
}
if (!$colour) {
throw new Exception("Colour not specified");
}
$this->weight = $weight;
$this->colour = $colour;
}
...
}
A constructor is optional but can execute arbitrary code.
You can give dynamic variables to your class:
with:
public function __construct(name, amount){
$this->name = name;
$this->weight = amount;
}
You can use your class for "bill" and "joe" and use different values of amounts.
Also you can make sure that you class will always has all it needs, for example a working database connection: You constructor should always demand all needs:
public function __construct(database_connection){
[...]
}

Categories