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
Related
I've written code that reads data from a cURL source which then processes it to extract records of data.
Each record becomes an instance of an object with several variables set from the data. A function extracts all the data and returns an array of objects.
The problem is that all of the objects have the same value which is the last record to be read from the source data.
After some testing I realize this is a reference problem. Data is read from the source and then assigned to an object which is then added to the array. The same object is reused in a loop that cycles through all the records in the source. Whenever this object is updated all previous values in the objects in the array are also reset to the newest value as they continue to reference the object when it is updated.
How can I make all the values independent?
function get_object_array () {
//reads raw data from cRUL source, returns array of objects
//array to hold objects
obj_arr = [];
//raw data has been split into array called $record, one element for each object
//loops through $record array
foreach ($record as $rec) {
//splits $rec into array of data called $data
//creates new object, but problem here as this object
//is being referenced by all values so last value
//changes all previous objects in array
$obj = new SaleItem();
//populates object with record data array
$obj->set_data($data);
//add object to array
$obj_arr [] = $obj;
}
return $obj_arr;
}
Update: Here is the function to set the data:
function set_data (array $arr) {
global $order_num, $name, $price, $cprice, $cheapest, $category;
try {
$order_num = (int)$arr[0];
$name = $arr[1];
$price = (float)$arr[2];
$cprice = (float)$arr[3];
$cheapest = $this->$price <= $this->$cprice ? true : false;
$category = $arr[5];
return true;
}
catch (Exception $ex) {
echo $ex;
return false;
}
}
Update: Full class code:
class SaleItem {
public $order_num = 12;
public $name = "";
public $price = 3.4;
public $cprice = 5.6;
public $cheapest = true;
public $category = "No Category";
function set_data (array $arr) {
try {
$this->order_num = (int)$arr[0];
$this->name = $arr[1];
$this->price = (float)$arr[2];
$this->cprice = (float)$arr[3];
$this->cheapest = $price <= $cprice ? true : false;
$this->category = $arr[5];
return true;
}
catch (Exception $ex) {
echo $ex;
return false;
}
}
function get_data () {
echo $this->order_num . ' num<br/>';
echo $this->name . ' name<br/>';
echo $this->price . ' price<br/>';
echo $this->cprice . ' cprice<br/>';
echo $this->cheapest . ' cheapest<br/>';
echo $this->category . ' category<br/>';
echo '<br/>';
}
}//end SaleItem class
You are using global variables instead of members. Remove
global $order_num, $name, $price, $cprice, $cheapest, $category;
From the function and preface each assignment with $this->
$this->order_num = (int)$arr[0];
$this->name = $arr[1];
$this->price = (float)$arr[2];
$this->cprice = (float)$arr[3];
$this->cheapest = $this->price <= $this->cprice;
$this->category = $arr[5];
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].
is there a way to achieve this in PHP?
echo list_args('a_user_defined_function_name_here_such_as_say_hello');
and this outputs something like
$first_name
$last_name
for a function defined as;
function say_hello($first_name, $last_name){
echo "Hello $first_name $last_name";
}
So basically, what I'm looking for is a function explainer or something of that sort... & if that thing can get into a php doc based comment extractor. that would be even better..
You could use the ReflectionFunction class to do this:
function list_args($name) {
$list = "";
$ref = new ReflectionFunction($name);
foreach ($ref->getParameters() as $param) {
$list .= '$' . $param->getName() . "\n";
}
return $list;
}
You can try ReflectionFunction.
function list_args($function) {
$func = new ReflectionFunction($function);
$res = array();
foreach ($func->getParameters() as $argument) {
$res[] = '$' . $argument->name;
}
return $res;
}
print_r(list_args('say_hello')); // outputs Array ( [0] => $first_name [1] => $last_name )
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
I'm currently learning php, and I'm testing out oop and classes.
My code is:
<?php
require('user.php');
$user = new User($username);
$projects = $user->getProjects();
for ($n = 0; $n<count($projects); $n++) {
echo "<li>";
echo "<a id=\"menu_pages\" href=\"\"><img src=\"../images/types/project.png\"/>" . $projects[$n]->name . "</a>";
echo "<ul>";
$items = $user->getItems($n);
for ($i = 0; $i<count($items); $i++) {
echo "<li><img src=\"../images/types/" . $items[$i]->type . ".png\"/>" . $items[$i]->name . "</li>";
}
echo "</ul>";
echo "</li>";
}
?>
and I'm getting the error:
Fatal error: Cannot redeclare class Item in /home/ios/public_html/classes/item.php on line 2
I found that its because I'm using
$items = $user->getItems($n);
in a loop. Because if I change it to
$items = $user->getItems(1);
it works. I cannot really figure out anyway of getting around the error.
Help please :)
Thanks in advance.
The methods:
function getItems($parent,$type = NULL) {
$items = array();
$username = $this->uname;
$userid = $this->getId($username);
include('classes/config.php');
if ($type != NULL) {
}
require_once('classes/item.php');
foreach ($pdo->query($sql) as $row) {
$instance = new Item();
$instance->name = $row['name'];
$instance->id = $row['id'];
$instance->type = $row['type'];
$instance->parent_id = $row['parent_id'];
$items[] = $instance;
unset($instance);
}
function getProjects() {
$projects = array();
$username = $this->uname;
$userid = $this->getId($username);
include('classes/config.php');
require_once('classes/project.php');
foreach ($pdo->query($sql) as $row) {
$proj = new Project();
$proj->name = $row['name'];
$proj->id = $row['id'];
$projects[] = $proj;
unset($proj);
}
return $projects;
}
edit:
its still not working with changing it. The code goes through with no errors, but now what should be under the first is under the second and the first is blank. See any issues in my logic?
Use require_once while including files with classes definition (I guess this will be somewhere in getItems()) or organize your files and define magic function __autoload() that will load it for you when used.
After looking into provided source, I doubt that this works for more than one row...
Here you create instance of Item before even checking if there are any items, and after first loop $instance is destroyed:
require('classes/item.php');
$instance = new Item();
foreach ($pdo->query($sql) as $row) {
$instance->name = $row['name'];
$instance->id = $row['id'];
$instance->type = $row['type'];
$instance->parent_id = $row['parent_id'];
$items[] = $instance;
unset($instance);
}
This should look like:
require_once('classes/item.php');
foreach ($pdo->query($sql) as $row) {
$instance = new Item();
$instance->name = $row['name'];
$instance->id = $row['id'];
$instance->type = $row['type'];
$instance->parent_id = $row['parent_id'];
$items[] = $instance;
unset($instance);
}
So for every item new instance is created.
change it to require_once('user.php'); and it won't try to execute user.php on each pass.
It's hard to say withut seeing what's in getItems() function, but it is possible that it includes a file where Item class is defined in a loop, which triggers this error. Try using require_once() instead.
The error message points to a duplicate class definition (The blueprint that starts with Class classname).
If you are pointing at the correct line of code - I'm not competely convinced you are - I'm pretty sure that $user->getItems() includes a PHP file, in which the class is redefined.
The immediate problem can be fixed using require_once() or include_once() but you should probably change your getItems function so that the class definition is loaded elsewhere in the first place.
I'll guess that the getItems() function on the User class probably has a line something like:
require('item.php');
if you change that to:
require_once('item.php');
you should be good to go.
(if I'm wrong about that, then please post the code for the getItems() function, so we can diagnose further).