PHP - Add function data with dots [duplicate] - php

This question already has answers here:
Method Chains PHP OOP
(3 answers)
Closed 8 years ago.
I have this working sample code as an example...
function get_childs() {
$array = array(1 => 'item1', 2 => 'item2', 3 => 'item3');
return $array;
}
function add( $array, $item ) {
$array[] = $item;
return $array;
}
function array_delete( $array, $key ) {
unset( $array[$key] );
return $array;
}
$result_array = array_delete( add( get_childs(), 'test' ), 2 );
print_r( $result_array );
Change to arrows instead
Right now a part of the code looks like this (quite ugly):
array_delete( add( get_childs(), 'test' ), 2 );
I have seen on the web that it is possible to do it someting like this instead:
get_childs().add('test').delete(2);
Much more beautiful. How is it done?
A sidenote
I have seen that the functions called this way can be repeated like this:
get_childs().add('something1').add('something2').add('something3');

The easiest way is move this functionality to class, eg:
class MyCollection
{
private $arr;
public function create_childs()
{
$this->arr = array(1 => 'item1', 2 => 'item2', 3 => 'item3');
return $this;
}
public function get_childs()
{
return $this->arr;
}
public function add($item)
{
$this->arr[] = $item;
return $this;
}
public function delete($key)
{
unset($this->arr[$key]);
return $this;
}
}
$collection = new MyCollection();
print_r($collection->create_childs()->add("test")->delete(2)->get_childs());

Related

Dynamic assignment of property names based on array values

I am trying to create a class that is going to generate dynamic class properties according to a user input.
There will be an array created from user input data. This array should work as an example:
$array = array(
# The boolean values are not relevant in this example
# The keys are important
'apple' => true,
'orange' => false,
'pear' => false,
'banana' => true,
);
Right now I want to create a new class with the array keys as the class properties:
class Fruit {
public $apple;
public $orange;
public $pear;
public $banana;
(etc.)
}
I had to manually write down all four properties now.
Is there a way to make it automated?
<?php
class MyClass
{
public function __construct ($config = [])
{
foreach ($config as $key => $value) {
$this->{$key} = $value;
}
}
}
$myClass = new MyClass(['apple' => 1, 'orange' => 2]);
echo $myClass->apple;
?>
this should help you
Here you go,
I put a few bonus things in there:
class MyClass implements Countable, IteratorAggregate
{
protected $data = [];
public function __construct (array $data = [])
{
foreach ($data as $key => $value) {
$this->{$key} = $value;
}
}
public function __set($key, $value){
$this->data[$key] = $value;
}
public function __get($key)
{
if(!isset($this->{$key})) return null; //you could also throw an exception here.
return $this->data[$key];
}
public function __isset($key){
return isset($this->data[$key]);
}
public function __unset($key){
unset($this->data[$key]);
}
public function __call($method, $args){
$mode = substr($method, 0, 3);
$property = strtolower(substr($method, 3)); //only lowercase properties
if(isset($this->{$property})) {
if($mode == 'set'){
$this->{$property} = $args[0];
return null;
}else if($mode == 'get'){
return $this->{$property};
}
}else{
return null; //or throw an exception/remove this return
}
throw new Exception('Call to undefined method '.__CLASS__.'::'.$method);
}
//implement Countable
public function count(){
return count($this->data);
}
//implementIteratorAggregate
public function getIterator() {
return new ArrayIterator($this->data);
}
}
Test it:
$myClass = new MyClass(['one' => 1, 'two' => 2]);
echo $myClass->two."\n";
//Countable
echo count($myClass)."\n";
//dynamic set
$myClass->three = 3;
echo count($myClass)."\n";
//dynamic get/set methods. I like camel case methods, and lowercase properties. If you don't like that then you can change it.
$myClass->setThree(4);
echo $myClass->getThree()."\n";
//IteratorAggregate
foreach($myClass as $key=>$value){
echo $key.' => '.$value."\n";
}
Outputs
2 //value of 2
2 //count of $data
3 //count of $data after adding item
4 //value of 3 after changing it with setThree
//foreach output
one => 1
two => 2
three => 4
Test it online
Disclamer
Generally though it's better to define the class by hand, that way things like IDE's work. You may also have issues because you won't necessarily know what is defined in the class ahead of time. You don't have a concrete definition of the class as it were.
Pretty much any method(at least in my code) that starts with __ is a PHP magic method (yes, that's a thing). When I first learned how to use these I thought it was pretty cool, but now I almost never use them...
Now if you want to create an actual .php file with that code in it, that's a different conversation. (it wasn't 100% clear, if you wanted functionality or an actual file)
Cheers.

Creating an array from variable names

When writing controllers for Symfony 2, I often need to pass quite a few variables to the template like return array('param1' => $param1, 'anotherBigParam' => $anotherBigParam, 'yetAnotherParam' => $yetAnotherParam);
With many parameters this ends up really long and ugly, so I thought about creating a helper function for it:
public function indexAction()
{
$param1 = 'fee';
$anotherBigParam = 'foe';
$yetAnotherParam = 'fum';
return $this->vars('param1', 'anotherBigParam', 'yetAnotherParam');
}
private function vars() {
$arr = array();
foreach(func_get_args() as $arg) {
$arr[$arg] = $$arg;
}
return $arr;
}
Is there some kind of drawback or risk from doing this? Does PHP or Symfony 2 already provide a better or cleaner way to achieve the same result?
There is a native way of doing it: compact
$one = 'ONE';
$two = 'TWO';
$a = compact( 'one', 'two' );
print_r( $a );
/*
Array
(
[one] => ONE
[two] => TWO
)
*/
You're looking for compact.
public function indexAction()
{
$param1 = 'fee';
$anotherBigParam = 'foe';
$yetAnotherParam = 'fum';
return compact('param1', 'anotherBigParam', 'yetAnotherParam');
}

How do I fill an object in PHP from an Array

Suppose I have:
class A{
public $one;
public $two;
}
and an array with values:
array('one' => 234, 'two' => 2)
is there a way to have an instance of A filled with the right values from the array automatically?
You need to write yourself a function for that. PHP has get_object_varsDocs but no set counterpart:
function set_object_vars($object, array $vars) {
$has = get_object_vars($object);
foreach ($has as $name => $oldValue) {
$object->$name = isset($vars[$name]) ? $vars[$name] : NULL;
}
}
Usage:
$a = new A();
$vars = array('one' => 234, 'two' => 2);
set_object_vars($a, $vars);
If you want to allow for bulk-setting of attributes, you can also store them as a property. It allows you to encapsulate within the class a little better.
class A{
protected $attributes = array();
function setAttributes($attributes){
$this->attributes = $attributes;
}
public function __get($key){
return $this->attributes[$key];
}
}
#hakre version is quite good, but dangerous (suppose an id or password is in thoses props).
I would change the default behavior to that:
function set_object_vars($object, array $vars) {
$has = get_object_vars($object);
foreach ($has as $name => $oldValue) {
array_key_exists($name, $vars) ? $object->$name =$vars[$name] : NULL;
}
}
here, the previous properties that are not in the $vars array are not affected.
and if you want to set a prop to null on purpose, you can.
Yes there is.
You could use a pass thru method.
For example:
class A {
public $one, $tow;
function __construct($values) {
$this->one = $values['one'] ?: null;
$this->two = $values['two'] ?: null;
}
}
$a = new A(array('one' => 234, 'two' => 2));

Array key as string and number

How to make arrays in which the key is number and string.
<?php
$array = array
(
'test' => 'thing',
'blah' => 'things'
);
echo $array[0]; // thing
echo $array[1]; // things
echo $array['test']; // thing
echo $array['blah']; // things
?>
$array = array_values($array);
but why would you need that? can you extend your example?
You could use array_keys to generate a lookup array:
<?php
$array = array
(
'test' => 'thing',
'blah' => 'things'
);
$lookup = array_keys ($array);
// $lookup holds (0=>'test',1=>'blah)
echo $array[$lookup[0]]; // thing
echo $array[$lookup[1]]; // things
echo $array['test']; // thing
echo $array['blah']; // things
?>
You could implement your own class that "implements ArrayAccess"
For such class you can manually handle such behaviour
UPD: implemented just for fun
class MyArray implements ArrayAccess
{
private $data;
private $keys;
public function __construct(array $data)
{
$this->data = $data;
$this->keys = array_keys($data);
}
public function offsetGet($key)
{
if (is_int($key))
{
return $this->data[$this->keys[$key]];
}
return $this->data[$key];
}
public function offsetSet($key, $value)
{
throw new Exception('Not implemented');
}
public function offsetExists($key)
{
throw new Exception('Not implemented');
}
public function offsetUnset($key)
{
throw new Exception('Not implemented');
}
}
$array = new MyArray(array(
'test' => 'thing',
'blah' => 'things'
));
var_dump($array[0]);
var_dump($array[1]);
var_dump($array['test']);
var_dump($array['blah']);

PHP Is there anyway I can simulate an array operator on the return value of a function [duplicate]

This question already exists:
Closed 11 years ago.
Possible Duplicate:
Any way to access array directly after method call?
In C# and other languages, I can do something like this
$value = $obj->getArray()[0];
But not in PHP. Any workarounds or am I doomed to do this all the time?
$array = $obj->getArray();
$value = $array[0];
No, you can't do it without using array_shift (Which only gets the first element). If you want to access the third or fourth, most likely you'd want to do a function like this:
function elemnt($array, $element)
{
return $array[$element];
}
$value = element($obj->getArray(), 4);
Also, see this question, as it is an exact duplicate: Any way to access array directly after method call?
I think you are doomed to do it that way :(
You can do this:
$res = array_pop(array_slice(somefunc(1), $i, 1));
If this is a one-off or occasional thing where the situation in your example holds true, and you're retrieving the first element of the return array, you can use:
$value = array_shift($obj->getArray());
If this is a pervasive need and you often need to retrieve elements other than the first (or last, for which you can use array_pop()), then I'd arrange to have a utility function available like so:
function elementOf($array, $index = 0) {
return $array[$index];
}
$value = elementOf($obj->getArray());
$otherValue = elementOf($obj->getArray(), 2);
Well, maybe this could help you, in php spl, pretty usefull, you can make you a Special Array for you:
<?php
class OArray extends ArrayObject{
public function __set($name, $val) {
$this[$name] = $val;
}
public function __get($name) {
return $this[$name];
}
}
class O{
function __construct(){
$this->array = new OArray();
$this->array[] = 1;
$this->array[] = 2;
$this->array[] = 3;
$this->array[] = 4;
}
function getArray(){
return $this->array;
}
}
$o = new O();
var_dump( $o->getArray()->{1} );
<?php
class MyArray implements Iterator ,ArrayAccess
{
private $var = array();
//-- ArrayAccess
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->var[] = $value;
} else {
$this->var[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->var[$offset]);
}
public function offsetUnset($offset) {
unset($this->var[$offset]);
}
public function offsetGet($offset) {
return isset($this->var[$offset]) ? $this->var[$offset] : null;
}//-- Iterator
public function __construct($array){
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
reset($this->var);
}
public function current() {
return current($this->var);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() !== false);
}
}
$values = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
$it = new MyArray($values);
foreach ($it as $a => $b) {
print "$a: $b<br>";
}
echo $it["one"]."<br>";?>

Categories