My php example returns an array that works, but I would like to keep everything inside "class CreateAccount".
This is the way I do it today, and it doesn't look so good but it works. Is there a better way of doing it?
<?php
class CreateAccount {
public function __construct($id,$namne,$fromdate,$group,$comment,$firstnamne,$org,$sid,$todate)
{
$this->countrows = null;
$this->id = $id;
$this->namne = $namne;
$this->fromdate = $fromdate;
$this->group = $group;
$this->comment = $comment;
$this->firstname = $firstnamne;
$this->org = $org;
$this->sid = $sid;
$this->todate = $todate;
}
}
/* Fill your Contact Object */
$contact = new CreateAccount("x6529","Jon Doe","2019-01-16","STD_GROUP","Guest User","Helen Doe","HQ","200410201234","2019-01-17");
/* Set your parameters for the request */
$params = array(
"application" => 'api',
"account" => $contact,
);
print_r($params);
?>
Array
(
[application] => api
[account] => CreateAccount Object
(
[countrows] =>
[id] => x6529
[namne] => Jon Doe
[fromdate] => 2019-01-16
[group] => STD_GROUP
[comment] => Guest User
[firstname] => Helen Doe
[org] => HQ
[sid] => 200410201234
[todate] => 2019-01-17
)
)
PHP have a function get_object_vars to get all the properties of a object. And because you're making dynamic properties in constructor. So, we defined a method getAccount which will get all the properties in an array $properties then we iterate through this and put all info in one array $account and finally we return this array.
<?php
class CreateAccount {
public function __construct($id,$namne,$fromdate,$group,$comment,$firstnamne,$org,$sid,$todate)
{
$this->countrows = null;
$this->id = $id;
$this->namne = $namne;
$this->fromdate = $fromdate;
$this->group = $group;
$this->comment = $comment;
$this->firstname = $firstnamne;
$this->org = $org;
$this->sid = $sid;
$this->todate = $todate;
}
public function getAccount()
{
$properties = get_object_vars($this);
$account = [];
foreach($properties as $property)
{
$account[$property] = $this->{$property};
}
return $account;
}
}
/* Fill your Contact Object */
$contact = new CreateAccount("x6529","Jon Doe","2019-01-16","STD_GROUP","Guest User","Helen Doe","HQ","200410201234","2019-01-17");
/* Set your parameters for the request */
$params = array(
"application" => 'api',
"account" => $contact->getAccount(),
);
print_r($params);
?>
I ended up doling like this:
class CreateAccount {
public function __construct($application,$id,$name,$fromdate,$group,$comment,$firstname,$org,$sid,$todate)
{
$this->application = $application;
$this->gastkonto['countrows'] = null;
$this->gastkonto['id'] = $id;
$this->gastkonto['name'] = $name;
$this->gastkonto['fromdate'] = $fromdate;
$this->gastkonto['group'] = $group;
$this->gastkonto['comment'] = $comment;
$this->gastkonto['firstname'] = $firstname;
$this->gastkonto['org'] = $org;
$this->gastkonto['sid'] = $sid;
$this->gastkonto['todate'] = $todate;
}
}
/* Fill your Contact Object */
$contact = new CreateAccount("api","x6529","Jon Doe","2019-01-16","STD_GROUP","Guest User","Helen Doe","HQ","200410201234","2019-01-17");
print_r($contact);
Related
I have created a class to get user parameters like below, but im having trouble showing data.
Here is what I have done:
namespace App\Users;
class Person
{
public $_user;
public $_userDataParams;
public function __construct($user)
{
$this->_user = $user;
$this->_userDataParams = self::$this->getData();
}
public function function_1()
{
$obj[$this->_user]['user_fullname'] = 'John Doe';
$obj[$this->_user]['user_role'] = 'Button-Pusher';
$this->_userDataParams = $obj;
return $this->_userDataParams;
}
public function function_2()
{
$obj[$this->_user]['experience'] = '4 Months';
$obj[$this->_user]['experience_date'] = '2017-01-01';
$this->_userDataParams = $obj;
return $this->_userDataParams;
}
public function getData()
{
$this->_userDataParams = array_merge(self::$this->function_1(),self::$this->function_2());
return $this->_userDataParams;
}
}
echo "<pre>";
$person = new Person("john");
print_r($person);
This is what it prints :
App\Users\Person Object
(
[_user] => john
[_userDataParams] => Array
(
[john] => Array
(
[experience] => 4 Months
[experience_date] => 2017-01-01
)
)
)
I need to add to _userDataParams also function_1 array of data.
Can someone help please.
Thank you.
How can I iterate the private fields of a class without having an instance of it but just the class name?
get_object_vars requires an existing instance.
Using: ReflectionClass
you can simply do:
class Foo
{
public $public = 1;
protected $protected = 2;
private $private = 3;
}
$refClass = new \ReflectionClass('Foo');
foreach ($refClass->getProperties() as $refProperty) {
if ($refProperty->isPrivate()) {
echo $refProperty->getName(), "\n";
}
}
or hide the implementation using a utility function/method:
/**
* #param string $class
* #return \ReflectionProperty[]
*/
function getPrivateProperties($class)
{
$result = [];
$refClass = new \ReflectionClass($class);
foreach ($refClass->getProperties() as $refProperty) {
if ($refProperty->isPrivate()) {
$result[] = $refProperty;
}
}
return $result;
}
print_r(getPrivateProperties('Foo'));
// Array
// (
// [0] => ReflectionProperty Object
// (
// [name] => private
// [class] => Foo
// )
//
// )
I have an XML file with many member entries, formatted like so:
<staff>
<member>
<name></name>
<image></image>
<title></title>
<email></email>
<phone></phone>
<location></location>
<info></info>
<webTitle></webTitle>
<webURL></webURL>
</member>
</staff>
setup
I've created 2 PHP classes, DisplayStaff and Employee.
Employee creates an Employee object, with private properties outlined in the XML above.
DisplayStaff is a factory class. It loads the above XML file, iterates through it, creating an Employee instance for each <member> element in the XML. It stores the Employee object in an array, $Employees[].
On the page where I want to output the Employee information, I'd like to be able to reference it like so.
$Employees = new DisplayStaff();
$John = Employees['John'];
echo "Hello, my name is $John->name";
code
<?php
class DisplayStaff
{
private var $staffList;
private var $placeholderImg;
private var $Employees;
public function __construct() {
$staffList = simplexml_load_file("../data/staff.xml");
$placeholderImg = $staffList->placeholderImg;
foreach ( $staffList->member as $member ) {
$employee = formatEmployeeObj( $member );
array_push( $Employees, $employee );
}
return $Employees;
}
private function formatEmployeeObj( $memberXML ) {
$Employee = new Employee();
$Employee->set( $name, $memberXML->name );
$Employee->set( $image, $memberXML->image );
$Employee->set( $title, $memberXML->title );
$Employee->set( $email, $memberXML->email );
$Employee->set( $phone, $memberXML->phone );
$Employee->set( $location, $memberXML->location );
$Employee->set( $info, $memberXML->info );
$Employee->set( $webTitle, $memberXML->webTitle );
$Employee->set( $webURL, $memberXML->webURL );
return $Employee;
}
}
?>
<?php
class Employee
{
private var $name = "";
private var $image = "";
private var $title = "";
private var $email = "";
private var $phone = "";
private var $location = "";
private var $info = "";
private var $webTitle = "";
private var $webURL = "";
public function get($propertyName) {
if( property_exists($this, $propertyName) ) {
return $this->$propertyName;
}
else{
return null;
}
}
public function set($propertyName, $propertyValue) {
if( property_exists($this, $propertyName) ){
$this->$propertyName = $propertyValue;
}
}
}
?>
problem
I can't seem to get this working. I'm new to working with classes. What do I need to change to have my classes behave how I desire them to?
Thank you in advanced for any help.
Remove var from each of your class fields. That is redundant with public and also deprecated as of PHP5. More on this
The constructor should not return anything. It will automatically return the object in question. Note, however, that there is no way of accessing any of the DisplayStaff fields since they are all private with no accessor functions. You could use the universal accessors like you do in Employee, but is there a reason for not simply using public fields?
Any time you are referring to an method or property of an object within the class declaration, you need to use the $this keyword, i.e.
public function __construct() {
$this->staffList = simplexml_load_file("staff.xml");
$this->placeholderImg = $this->staffList->placeholderImg
foreach ( $this->staffList->member as $member ) {
$employee = $this->formatEmployeeObj( $member );
array_push( $this->Employees, $employee );
}
//no need for a return
}
Your Employee property accessor method (Employee->get()) takes a string as the first parameter, i.e. 'name'. $name is an undefined variable so it won't work.
You need to initialize your Employees array before you can push to it.
private $Employees = array();
Note that I left out many of the Employee properties and methods for the sake of brevity.
class StaffFactory
{
public $employees = array();
public function __construct($xml)
{
$xml = simplexml_load_file($xml);
foreach ( $xml->member as $member ) {
$this->employees[(string) $member->name] = new Employee((array) $member);
}
}
public function getEmployee($name)
{
if ( isset($this->employees[$name]) ) {
return $this->employees[$name];
}
return false;
}
}
class Employee {
public $email;
public $name;
public $title;
public function __construct(array $employee)
{
foreach ( $employee as $k => $v ) {
if ( property_exists($this, $k) ) {
$this->{$k} = $v;
}
}
return $this;
}
}
$staffFactory = new StaffFactory('staff.xml');
$john = $staffFactory->getEmployee('John');
if ( $john ) {
echo '<pre>';
print_r($staffFactory);
print_r($john);
print_r($john->email);
echo '</pre>';
}
I have below array result
Array ( [0] => Item Object ( [name:protected] => My Super Cool Toy [price:protected] => 10.99 ) )
I need to get [name:protected] => My Super Cool Toy from this array.
Please tell me how to get it,
I will paste my classes below
class ShoppingCart
{
private $items = array();
private $n_items = 0;
function addItem( Item $item )
{
$this->items[] = $item;
$this->n_items = $this->n_items + 1;
print_r($this->items);
}
}
and
class Item {
protected $name;
protected $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
echo "item is $this->name";
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
and
require_once('AddingMachine.php');
require_once('item.php');
//$arrayofnumbers = array(100,200);
$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));
$obname = new Item($items,44);
$obname->getName();
Thanks
If I got it correctly, you got this array in ShoppingCart class, in method addItem, so to access it you just use corresponding getter method, e.g.:
$this->items[0]->getName();
You can try :
$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));
foreach ( $objectname->getItems() as $item ) {
echo $item->getName(), PHP_EOL;
}
Modified Class
class ShoppingCart {
private $items = array();
private $n_items = 0;
function addItem(Item $item) {
$this->items[] = $item;
$this->n_items = $this->n_items + 1;
}
function getItems($n = null) {
return $n === null ? $this->items : (isset($this->items[$n]) ? : $this->items[$n]);
}
}
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