Declares values on objects and output the values - php

I need some guide or reference on how should I do this.
What I should do is, have a class structure named Cat and have a static method that outputs new object.
class Cat{
public $name;
public $age;
public $string;
static public function ToData($Cat) {
$input = "";
foreach ($Cat as $key => $value) {
$input .= "object: " . $key . "</br>";
}
return $input;
}
}
$name = "meow";
$age = "12";
$string = "'test', 'sample', 'help'";
$Cat = array($name, $age);
$output = Cat::ToData($Cat);
echo $output;
This is the best thing that I can come up with
here is the problem, they said I just used an array and not an object.
I used array because I have to put the values on the $Cat so it can be passed on the parameter.

Looks like it's an assignment on object-oriented programming concept in PHP. I believe this is what you're trying to accomplish, with comments explaining the steps.
class Cat{
public $name;
public $age;
// Output the attributes of Cat in a string
public function ToData() {
$input = "";
$input .= "object: name :".": ".$this->name." </br>";
$input .= "object: age :".": ".$this->age." </br>";
return $input;
}
}
$name = "meow";
$age = "12";
// Instantiate Cat
$Cat = new Cat();
$Cat->name = $name;
$Cat->age = $age;
// Output Cat's attributes
$output = $Cat->ToData();
echo $output;

if you want to set those values to the object here is what you do
...
foreach ($Cat as $key => $value) {
$this->$key = $value;
}
...
$name = "meow";
$age = "12";
$Cat = array("name"=>$name,"age"=> $age);
$cat = new Cat();
$cat->toData($Cat);
echo $cat->name;
// meow
Update:
Now i get a better idea what you are trying to do, this is how your class will look like:
class Cat{
public $name;
public $age;
public $string;
static public function ToData($Cat) {
$obj = new self();
$obj->name = $Cat["name"];
$obj->age = $Cate["age"];
$obj->string = $Cate["string"];
return $obj;
}
// echo
public function __toString(){
return "$this->name - $this->age - $this->string";
}
}
now you can set your values
$name = "meow";
$age = "12";
$string = "'test', 'sample', 'help'";
$Cat = array($name, $age,$string);
$output = Cat::ToData($Cat);
echo $output;
Note that $output is an object

Related

how to define new various in PHP function

I want to define new variable in a function .
function show()
{//for e.g
$name = "john";
$family = "cina";
$old = "45";
}
show();
echo "your name is $name ";//in another line
echo "your family is $family ";//in another line
echo "your old is $old ";//in another line
Thanks
You could also consider using list(); you'll have to make a slight change to your function but it'll work.
function show(){
$name = "john";
$family = "cina";
$old = "45";
return array($name,$family,$old);
}
list($name,$family,$old) = show();
echo $name;
echo $family;
echo $old;
Be aware that the order matters, the first value in the return array will be assigned to the first variable in the list(); and the second array value to the second variable in the list, and so on.
Write echo inside function as below
function show()
{
$name = "john";
$family = "cina";
$old = "45";
echo $name." ".$family." ".$old;
}
show();
function show()
{
$name = "john";
$family = "cina";
$old = "45";
return $name." ".$family." ".$old;
}
echo show();
This
Return it from your function like this
function show()
{//for e.g
$name = "john";
$family = "cina";
$old = "45";
return $name . " " . $family . " " . $old;
}
$result = show();
echo $result;
you can use also in the following way
function show()
{
$name = "john";
$family = "cina";
$old = "45";
return $name." ".$family." ".$old;
}
echo $res = show(); // john cina 45
This is how I should do it =)
<?php
function show()
{
$name = "john";
$family = "cina";
$old = "45";
echo $name." ".$family." ".$old;
}
show();
?>
As a general rule, don't do this. It's not very good and looks terrible, but this is what you need.
<?php
$name = null;
$family = null;
$old = null;
function show()
{
global $name, $family, $old;
$name = "john";
$family = "cina";
$old = "45";
}
show();
echo "your name is $name ".PHP_EOL;
echo "your family is $family ".PHP_EOL;
echo "your old is $old ".PHP_EOL;
I will recommend an alternative way of writing this (one of many). You can check other answers for different ways.
class Singleton {
public static $name;
public static $family;
public static $old;
}
function show()
{
Singleton::$name = "john";
Singleton::$family = "cina";
Singleton::$old = "45";
}
show();
echo "your name is ".Singleton::$name;//in another line
echo "your family is ".Singleton::$family;//in another line
echo "your old is ".Singleton::$old;//in another line

Need help on simple PHP loop to run on class objects

I am looking for a way to make this foreach loop run on the UserData objects.
<?php
echo '<pre>';
class UserData{
public $FName;
public $LName;
public $IP;
}
$user001 = new UserData();
$user002 = new UserData();
$user003 = new UserData();
$user001->FName = 'Erez';
$user001->LName = 'T';
$user001->IP = '192.168.0.1';
$user002->FName = 'Netali';
$user002->LName = 'Goz';
$user002->IP = '192.168.0.2';
$user003->FName = 'Charley';
$user003->LName = 'Abu Ben David';
$user003->IP = '192.168.0.3';
So up to here the class has the attributes picked up by the new objects above.
Now from this part below I'm using the get_object_vars to retrieve the UserData but I have no idea how to run it dynamically.
Can you help me with this in the shortest code possible with the most basic code?
(a for loop would be great!)
$vars = get_object_vars('UserData');
print_r($vars);
echo '<hr>';
foreach ($vars as $OP =>$OPVal){
echo $OP .' is '.$OPVal.'<br>';
}
You can disregard the print_r and echo's.
Thanks!
you can loop with this methode
for($x=1;$x<4;$x++){
$vars = get_object_vars(${'user00'.$x});
print_r($vars);
echo '<hr>';
foreach ($vars as $OP =>$OPVal){
echo $OP .' is '.$OPVal.'<br>';
}
echo '<hr>';
}
but, you better learn OOP concept first.
Instead of making individual instances of the object, create an array of objects, and add as many as you need.
You can also add a constructor for the class, to instantiate easier.
Example:
class UserData{
public $FName;
public $LName;
public $IP;
public function __construct($fname,$lname,$ip){
$this->FName = $fname;
$this->LName = $lname;
$this->IP = $ip;
}
}
//store your data in some arrays
$firstNames = array('Erez','Netali','Charley');
$lastNames = array('T','Goz','Abu Ben David');
$ips = array('192.168.0.1','192.168.0.2','192.168.0.3');
$users = array();
for ($i=0;$i<3;$i++){
// instantiate each new object using data from the above arrays
$users[] = new UserData($firstNames[$i],$lastNames[$i],$ips[$i]);
// or use your method
/*
$users[] = new UserData('Netali','Goz','192.168.0.2')
*/
}
// now iterate over your array of UserData objects and print their properties
foreach ($users as $user){
print $user->FName . ", " . $user->LName . ", " . $user->IP . PHP_EOL;
}
// outputs
Erez, T, 192.168.0.1
Netali, Goz, 192.168.0.2
Charley, Abu Ben David, 192.168.0.3

Php doing a for loop with OOP,can't figure out how

i have this code below:
<?php
class Product {
public $name;
public $desc;
public $price;
public $category;
public $qty;
public $model;
public $manufacturer;
function display() {
$output = '';
$output .= $this->name ."</br>";
$output .= $this->desc . "</br>";
$output .= $this->price "</br>";
$output .= $this->category "</br>";
$output .= $this->qty "</br>";
$output .= $this->model "</br>";
$output .= $this->manufacturer "</br>";
return $output;
}
}
$product = new Product();
$product->name = "Samsung galaxy s6";
$product->desc = "It's kind of good but meh";
$product->price = "1000 GBP";
$product->category = "Phones";
$product->qty = "Quantity:999";
$product->model = "Samsung s6";
$product->manufacturer = "Phone guys";
echo $product->display();
?>
So this function works without a problem by itself when i set the values in:
$product->name = "Samsung galaxy s6";
$product->desc = "It's kind of good but meh";
$product->price = "1000 GBP";
$product->category = "Phones";
$product->qty = "Quantity:999";
$product->model = "Samsung s6";
$product->manufacturer = "Phone guys";
So when i set all the values everything works,but my question is: Is it possible for me to make each one of those an array lets say i want to display 2 products in the browser
When I set the $product->name to $product->name = array("Samsubg","Iphone","Apple");
This by itself displays only **Apple* and i kind of get lost here on what to do
Thanks.
You normally would use a setter method to set variables and it would look like this if you wanted to set it as an array.
private name = array();
public function setName($name) {
$this->name[] = $name;
}
You would want to do this with all your variables. If you wanted to pass in an array you could loop through it and pass one at a time or pass the whole array you would want to set your setter function like this:
private name = array();
public function setName($name) {
$this->name = $name;
}
You could then set it by calling the method and passing in the array.
$product->setName($myArrayOfNames);
With OOP, it doesn't make sense to have a single object with fields that are arrays. That is just procedural programming in an object.
Instead, the fields of each object should describe the state of only the object itself. If you need an array to describe multiple products, then you simply make an array of the Product object.
$products = array();
$product_one = new Product();
$product_one->name = "Samsung galaxy s6";
$product_one->desc = "It's kind of good but meh";
$product_one->price = "1000 GBP";
$product_one->category = "Phones";
$product_one->qty = "Quantity:999";
$product_one->model = "Samsung s6";
$product_one->manufacturer = "Phone guys";
$product_two = new Product();
$product_two->name = "iPhone6";
$product_two->desc = "who knows";
$product_two->price = "10000 GBP";
$product_two->category = "Phones";
$product_two->qty = "Quantity: 1";
$product_two->model = "iPhone";
$product_two->manufacturer = "Apple";
$products[] = $product_one;
$products[] = $product_two;
foreach($products as $product) {
echo $product->display();
}
Define your array property in the class, here is a full working example.
class Body
{
private $name = array();
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$user = new Body();
$user->setName(array("Samsubg","Iphone","Apple"));
echo var_dump($user->getName()); This will dump an array, all you have to do is do a for loop over it or get the array values by index: $user->getName[0].

Echo a value from an array based on function parameters

I need to be able to echo a value from a private property in one of my classes if a method is called within the class. It's a little tricky to explain so let me demostrate and hopefully someone can fill in the blank for me :)
<?php
class test {
private $array['teachers']['classes'][23] = "John";
public function __construct($required_array) {
$this->array['teachers']['classes'][23] = "John";
$this->array['students'][444] = "Mary";
$this->echo_array($required_array);
}
public function echo_array($array) {
// Echo the value from the private $this->array;
// remembering that the array I pass can have either
// 1 - 1000 possible array values which needs to be
// appended to the search.
}
}
// Getting the teacher:
$test = new test(array('teachers','classes',23));
// Getting the student:
$test = new test(array('students',444));
?>
Is this possible?
$tmp = $this->array;
foreach ($array as $key) {
$tmp = $tmp[$key];
}
// $tmp === 'John'
return $tmp; // never echo values but only return them
An other approach to get value;
class Foo {
private $error = false,
$stack = array(
'teachers' => array(
'classes' => array(
23 => 'John',
24 => 'Jack',
)
)
);
public function getValue() {
$query = func_get_args();
$stack = $this->stack;
$result = null;
foreach ($query as $i) {
if (!isset($stack[$i])) {
$result = null;
break;
}
$stack = $stack[$i];
$result = $stack;
}
if (null !== $result) {
return $result;
}
// Optional
// trigger_error("$teacher -> $class -> $number not found `test` class", E_USER_NOTICE);
// or
$this->error = true;
}
public function isError() {
return $this->error;
}
}
$foo = new Foo();
$val = $foo->getValue('teachers', 'classes', 24); // Jack
// $val = $foo->getValue('teachers', 'classes'); // array: John, Jack
// $val = $foo->getValue('teachers', 'classes', 25); // error
if (!$foo->isError()) {
print_r($val);
} else {
print 'Value not found!';
}

OO PHP returning all private variables as variables on page

I have the following class, which has a lot of private variables.
class plantOfTheMonth {
//Declare which centre(s) are being used
private $centre = "";
//Declare the attributes of the current Plant Of The Month
private $name = "";
private $latinName = "";
private $image = "";
private $imageAlt = "";
private $imageLink = "";
private $strapLine = "";
private $description = "";
private $colour = "";
private $centres = "";
//Declare variables for error handling
private $issue = "";
private $issueCode = "";
public function __construct() {
}
public function returnAttributes() {
$list = ""; //Set an Empty List
foreach($this as $key => $value) {
decodeText($value); //decode performs a stripslashes()
$$key = $value; //Use a variable variable and assign a value to it
$list .= "'".$key."', "; //add it to the list for the compress()
}
$list .= substr($list, 0, -2); //Take the final ", " off
return compact($list); //return the list of variables as an array
}
}
I want to return all of the attributes as variables with their values, so that I can pre-fill a form field. I have a database query which fills all of the attributes (which works as proven by testing). In my pre-OO days, I retrieved the info from the db, put it into variables, then used compress() to send and extract() to get all the variables. Is this something that will work, as in the returnAttributes() method in my class?
Why make it so complicated? Here's an example with a lot less code which has the desired behaviour.
public function returnAttributes()
{
$list = array(); //Set an Empty List
foreach(array_keys(get_class_vars(__CLASS__)) as $key)
{
$list[$key] = $this->$key;
}
return $list;
}

Categories