methods of declaring multiple variables - php

I have the following blocks of code:
$ship = $this->get_address($this->dealer_num);
$bill = $this->get_address($this->bill_to_num);
$this->ship_name = $ship['CMNAME'];
$this->ship_address1 = $ship['CMLNE1'];
$this->ship_address2 = $ship['CMLNE2']!='' ? $ship['CMLNE2'] : NULL;
$this->ship_address3 = $ship['CMLNE2']!='' ? $ship['CMLNE3'] : NULL;
$this->ship_city = $ship['CMCITY'];
$this->ship_state = $ship['CMST'];
$this->ship_zip = $ship['CMZIP'];
$this->ship_country = $ship['CMCTRY'];
$this->bill_name = $bill['CMNAME'];
$this->bill_address1 = $bill['CMLNE1'];
$this->bill_address2 = $bill['CMLNE2']!='' ? $bill['CMLNE2'] : NULL;
$this->bill_address3 = $bill['CMLNE3']!='' ? $bill['CMLNE3'] : NULL;
$this->bill_city = $bill['CMCITY'];
$this->bill_state = $bill['CMST'];
$this->bill_zip = $bill['CMZIP'];
$this->bill_country = $bill['CMCTRY'];
Here is the definition of get_address:
private function get_address($key) {
$result = db_query('SELECT CMNAME, CMLNE1, CMLNE2,
CMLNE3, CMCITY, CMST, CMZIP, CMCTRY
FROM myTable
WHERE C1STKY = :key;',
array(':key' => $key));
$info = $result->fetch(PDO::FETCH_ASSOC);
return $info;
}
What are my alternatives for declaring these variables? I hate the big long lists of just variable declarations. Is there a more elegant way to declare these?

The way I ultimately fixed this problem was changing my class definition. Rather than having class properties for each address component, I simply changed my class definition to store the address as an associative array. It felt much cleaner that way.
Thus, the above code became
$this->shipping_address = $this->get_address($this->dealer_num);
$this->billing_address = $this->get_address($this->bill_to_num);

Related

PHP class fields are the same

I have a problem with PHP code.
Here is it:
class Note {
public $title = "";
public $text = "";
}
$note = new Note();
while($note_result = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$note->$title = $note_result["title"];
$note->$text = $note_result["text"];
}
The problem is that $note->$title and $note->$text have the same value. I tried assigning $note_result["..."] to two different variables and it worked, but I would like to use class to return variable as one.
Am I missing something? I been checking this code for half an hour and found nothing.

Could I automatically get a reference of arguments in a PHP function?

Currently, I am reviewing websites written ten years ago. These websites uses the old MySQL API for PHP. PHP hasn't been upgraded since version 5.3, that's why I need to rewrite each database request from the old API to PDO.
The original coder has create for each table an object that wraps INSERT,SELECT and UPDATE requests.
On tables with a lot of rows, it is very painful to quote for each object each argument of each wrapped request, and there a dozen of sites that I must revise !
So, I think about a way to reduce the time spent on quoting each argument of the function by getting these in a loop and quote each of them in two lines of code in each function...
After viewing PHP manual, it seems that there is no way to get a reference of a function arguments. I can copy or count them, but can't get any reference.
Have you got any ideas or tips that will make this job sucks less ?
Here is an example of what I shouldn't do :
public function insert($titre, $tva, $intra, $remise = 0,
$tx_remise = 0, $frais = 0, $code = 0, $nom = '',
$design = '', $adr = '', $cp = '', $ville = '',
$tel = '', $fax = '', $rcs = '', $marq = '',
$marq_g = '')
{
$ville = htmlspecialchars($ville);
$design = htmlspecialchars($design);
$nom = htmlspecialchars($nom);
$adr = htmlspecialchars($adr);
$marq = htmlspecialchars($marq);
$marq_g = htmlspecialchars($marq_g);
$titre = $this->db->quote($titre);
$tva = $this->db->quote($tva);
$intra = $this->db->quote($intra);
$remise = $this->db->quote($remise);
$tx_remise = $this->db->quote($tx_remise);
$frais = $this->db->quote($frais);
$code = $this->db->quote($code);
$cp = $this->db->quote($cp);
$tel = $this->db->quote($tel);
$fax = $this->db->quote($fax);
$rcs = $this->db->quote($rcs);
And what I approximately want to do :
public function insert(...)
{
foreach($function->argumentsReference as $ref)
$ref = quote($ref)
Of course $function isn't a real object, it is just a way to explain my idea with code.
Thanks.
You can use get_defined_vars to retrieve an associative array of all variables in scope, so as long as you use this at the top of your function then you'll effectively have a named copy of all the function arguments. Note that this is different to using func_get_args, which won't contain any default arguments if not provided in the call.
You can apply some logic to all the arguments (quoting, etc) using something like:
<?php
function foo($a, $b, $c) {
foreach (get_defined_vars() as $key => $value) {
${$key} = $value * 2;
}
echo implode(', ', [$a, $b, $c]);
}
foo(1, 2, 3);
// 2, 4, 6
If you took PDO you need to use PDO::prepare and you get that rid of that problem.
What about this (PHP 5.6 or higher required):
function insert(...$data){
var_dump($data); // This returns an array of all passed arguments.
array_map($data, function($datum){
return htmlspecialchars($datum);
}
// Boom, now all entries in the $data array are "htmlspecialcharsified".
list($titre, $tva, $intra, $remise, $tx_remise, $frais, $code, $nom, $design, $adr, $cp, $ville, $tel, $fax, $rcs, $marq, $marq_g) = $data;
// As long as all parameters are passed in the correct order, you now have the desired variables available.
// Do your magic here
}

Parsing empty XML elements in PHP

PHP newbie here. I'm parsing a long XML file, setting each tag to a variable. If the element's tag is empty, I want to assign it the value "N/A"
I'm wondering if there's a more concise way to do this than my current approach:
$elements = array()
$propertyOwner = $report->PropertyProfile->PrimaryOwnerName[0];
array[] = $propertyOwner;
$propertyAddress = $report->PropertyProfile->SiteAddress[0];
array[] = $propertyAddress;
...
for($i=0; $i<count($elements); $i++) {
if (array[i] === '') {
array[i] = 'N/A');
}
}
The way the code was written originally (without $s in front of each variable) you'd probably be getting errors all day. Hope this helps simplify:
$array[] = '';
$elements = array();
$propertyOwner = $report->PropertyProfile->PrimaryOwnerName[0];
$elements[] = $propertyOwner;
$propertyAddress = $report->PropertyProfile->SiteAddress[0];
$elements[] = $propertyAddress;
//...
// IF THEN ELSE
$array[] = !empty($elements) ? $elements : 'N/A';

Get the first element of an array that is defined and not null

I would like to assign a variable that is the first not null element from another set of variables. Much like the conditional assignment in ruby ||=. For example:
<?php
$result = null;
$possibleValue1 = null;
// $possibleValue2 not defined
$possibleValue3 = 'value3';
if (isset($possibleValue1) && !is_null($possibleValue1)) {
$result = $possibleValue1;
} else if (isset($possibleValue2) && !is_null($possibleValue2)) {
$result = $possibleValue2;
} else if (isset($possibleValue3) && !is_null($possibleValue3)) {
$result = $possibleValue3;
}
Is there a way to do this simply in php, like so (if possible, I would like to avoid creating a function and just use functions from the php library):
$result = firstNotNull(array($possibleValue1, $possibleValue2, $possibleValue3));
I think the shortest way is:
$result = current(array_filter(array($possibleValue1, $possibleValue2, $possibleValue3)));
If all $possibleValues are definitely set:
$possibleValues = array($possibleValue1, $possibleValue2, ...);
If they may not be set:
$possibleValues = compact('possibleValue1', 'possibleValue2', ...);
Then:
$result = reset(array_filter($possibleValues, function ($i) { return $i !== null; }));
Do not know about such a function in PHP but why not creating Your own?
function getFirstNotNullValue($values = array()) {
foreach($values as $val)
if($val) return $val;
return false;
}

PHP - Dynamically reference object property

I have code like :
$result = $object->property[0];
but I want to do something like :
if ($a) {
$property = 'blue' }
else {
$property = 'black'}
$result = $object->$property[0];
However this give me a Cannot use string offset as an array error.
Any pointers (no pun intended) appreciated.
Use braces:
$result = $object->{$property}[0];
$result = $object->{$property}

Categories