PHP class arrays - php

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.

Related

Is there a cleaner way of creating an array?

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

Sorting array of objects by function in PHP

Let's say I have an object called ACCOUNT like:
class ACCOUNT
{
private $contact;
public function getContact();
}
and another object CONTACT:
class CONTACT
{
private $lastName;
public function getLastName()
{
return $this->lastName;
}
}
Then I create an array of these objects $accountArray = ACCOUNT::get();
How can I sort this array alphabetically by something like $account->getContact()->getLastName();?
What I've tried:
class Account
{
private $contact;
public function getContact();
public static function cmp($a,$b)
{
$al = strtolower($a->getContact()->getLastName());
$bl = strtolower($b->getContact()->getLastName());
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
public static function sortByLastName($accountArray)
{
usort($moACOUNTArray, array('ACCOUNT', 'cmp'));
}
}
But I get this error:
Call to undefined method ACCOUNT::getContact()
You can use usort function of PHP, like mentioned in comments. There is self-explaining example:
Try this code:
<?php
class ACCOUNT
{
private $contact;
public function getContact()
{
return $this->contact;
}
public function setContact($v)
{
$this->contact = $v;
}
}
class CONTACT
{
private $lastName;
public function getLastName()
{
return $this->lastName;
}
public function setLastName($v)
{
$this->lastName = $v;
}
}
//create data for testing
$c1 = new CONTACT;
$c1->setLastName('aaaa');
$a1 = new ACCOUNT;
$a1->setContact($c1);
$c2 = new CONTACT;
$c2->setLastName('zzz');
$a2 = new ACCOUNT;
$a2->setContact($c2);
$c3 = new CONTACT;
$c3->setLastName('ggg');
$a3 = new ACCOUNT;
$a3->setContact($c3);
$array = array($a1, $a2, $a3);
//making sort
function cmp($a, $b)
{
return strcmp($a->getContact()->getLastName(), $b->getContact()->getLastName());
}
usort($array, "cmp");
//showing sort result
echo '<pre>';
print_r($array);
Result is:
Array
(
[0] => ACCOUNT Object
(
[contact:ACCOUNT:private] => CONTACT Object
(
[lastName:CONTACT:private] => aaaa
)
)
[1] => ACCOUNT Object
(
[contact:ACCOUNT:private] => CONTACT Object
(
[lastName:CONTACT:private] => ggg
)
)
[2] => ACCOUNT Object
(
[contact:ACCOUNT:private] => CONTACT Object
(
[lastName:CONTACT:private] => zzz
)
)
)

How to create instances with strings in php

I have a class called the 'analyst' and he has many 'analysers'. The analysers go looking for certain patterns in a given input.
For now, I create the instances of the 'analysers' in the constructor function of the anaylser like this:
<?php
class analyser {
protected $analysers = array();
public function __construct() {
$analyser1 = new Analyser1();
$this->analysers[] = $analyser1;
$analyser2 = new Analyser1();
$this->analysers[] = $analyser2;
...
}
This works for a limited amount of analysers but I want to create an array ('analyser1', 'analyser2', ...) that will be used in a loop to create all the needed instances. Is this possible or do I need to create every instance manually?
public function __construct() {
foreach ($names as $analyser){
$instance = new $analyser();
$this->analysers[] = $instance;
}
How can i do this ?
This should be straightforward - furthermore you could use nested associative array data to add some initial properties to each object, for example, you might want to give each object a name property:
<?php
class Analyser1
{
protected $name;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$analyserData = [
['name' => 'analyser1'],
['name' => 'analyser2'],
['name' => 'analyser3'],
];
$analysers = [];
foreach ($analyserData as $data) {
$obj = new Analyser1();
$name = $data['name'];
$obj->setName($name);
$analysers[$name] = $obj;
echo 'created ' . $obj->getName() . PHP_EOL;
}
print_r($analysers);
Yields:
created analyser1
created analyser2
created analyser3
Array
(
[analyser1] => Analyser1 Object
(
[name:protected] => analyser1
)
[analyser2] => Analyser1 Object
(
[name:protected] => analyser2
)
[analyser3] => Analyser1 Object
(
[name:protected] => analyser3
)
)
Example here: https://eval.in/133225
Hope this helps! :)
You can use this simple code:
public function __construct() {
for ($i=1; $i<=10; $i++){
// if you want associative array, you should use this part
$key = 'analyser' . $i;
$this->analysers[$key] = new Analyser1();
}
}
And it would create 10 instances of class Analyser1 in array $this->analysers

How can I get all the public property values of a 'last descendant' object in php?

The code below makes this easier to explain :
<?php
class a
{
public $dog = 'woof';
public $cat = 'miaow';
private $zebra = '??';
}
class b extends a
{
protected $snake = 'hiss';
public $owl = 'hoot';
public $bird = 'tweet';
}
$test = new b();
print_r(get_object_vars($test));
Currently this returns:
Array
(
[owl] => hoot
[bird] => tweet
[dog] => woof
[cat] => miaow
)
what can I do to find properties that were only defined or set in class b (eg just owl and bird)?
Use ReflectionObject for this:
$test = new b();
$props = array();
$class = new ReflectionObject($test);
foreach($class->getProperties() as $p) {
if($p->getDeclaringClass()->name === 'b') {
$p->setAccessible(TRUE);
$props[$p->name] = $p->getValue($test);
}
}
print_r($props);
Output:
Array
(
[snake] => hiss
[owl] => hoot
[bird] => tweet
)
getProperties() will return all properties of the class. I'm using $p->getDeclaringClass() afterwards to check if the declaring class is b
Additionally this can be generalized to a function:
function get_declared_object_vars($object) {
$props = array();
$class = new ReflectionObject($object);
foreach($class->getProperties() as $p) {
$p->setAccessible(TRUE);
if($p->getDeclaringClass()->name === get_class($object)) {
$props[$p->name] = $p->getValue($object);
}
}
return $props;
}
print_r(get_declared_object_vars($test));

using the magic __set() method with 2D arrays

If I have the following registry class:
Class registry
{
private $_vars;
public function __construct()
{
$this->_vars = array();
}
public function __set($key, $val)
{
$this->_vars[$key] = $val;
}
public function __get($key)
{
if (isset($this->_vars[$key]))
return $this->_vars[$key];
}
public function printAll()
{
print "<pre>".print_r($this->_vars,true)."</pre>";
}
}
$reg = new registry();
$reg->arr = array(1,2,3);
$reg->arr = array_merge($reg->arr,array(4));
$reg->printAll();
Would there be an easier way to push a new item onto the 'arr' array?
This code: 'array[] = item' doesn't work with the magic set method, and I couldn't find any useful info with google. Thanks for your time!
If you have:
$reg = new registry();
$reg->arr = array(1,2,3);
$reg->arr = 4;
And you're expecting:
Array
(
[arr] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
)
All you need to do is update your __set method to:
public function __set($key, $val){
if(!array_key_exists($key, $this->_vars)){
$this->_vars[$key] = array();
}
$this->_vars[$key] = array_merge($this->_vars[$key], (array)$val);
}
You need to alter the definition of __get() so that it returns by reference:
public function &__get($key) {
return $this->_vars[$key];
}

Categories