PHP Array with Private Vars - php

How i can read this array alone $var['shipment_number'] don't work?
EinName\EINUNTERNEHMEN\Response Object
(
[shipment_number:EinName\EINUNTERNEHMEN\Response:private] => 222253010000075775
[piece_number:EinName\EINUNTERNEHMEN\Response:private] =>
[label:EinName\EINUNTERNEHMEN\Response:private] => https://cig.Einurl.com
[returnLabel:EinName\EINUNTERNEHMEN\Response:private] =>
[exportDoc:EinName\EINUNTERNEHMEN\Response:private] =>
[labelType:EinName\EINUNTERNEHMEN\Response:private] => URL
[sequenceNumber:EinName\EINUNTERNEHMEN\Response:private] => 1
[statusCode:EinName\EINUNTERNEHMEN\Response:private] => 0
[statusText:EinName\EINUNTERNEHMEN\Response:private] => ok
[statusMessage:EinName\EINUNTERNEHMEN\Response:private] => Der Webservice wurde ohne Fehler ausgeführt.
[version:EinName\EINUNTERNEHMEN\Version:private] => 2.2
[mayor:EinName\EINUNTERNEHMEN\Version:private] => 2
[minor:EinName\EINUNTERNEHMEN\Version:private] => 2
)
Code link:
https://pastebin.com/uDm6neRt

What you have there is an object, specifically an instance of EinName\EINUNTERNEHMEN\Response. Further, the properties are private, so you can only access them directly from inside the class.
See this example:
<?php
class Response {
private $var;
public function __construct($var) {
$this->var = $var;
}
public function getVar() {
return $this->var;
}
}
$res = new Response("test");
echo $res->getVar(); // test
echo $res->var; // fatal error, attempting to access a private property
Demo
So, if you don't have access to the class, to get the properties you need to use the getter, if it exists. Check the documentation of your Response class, by convention it should look like this:
echo $var->getShipmentNumber();

Related

In PHP classes is it possible to create a private variable inside of a function?

In using PHP classes I have noticed that inside a class when I define a variable in a function as a property of that class in the $this->variablename way it automatically becomes a public variable of that class.
class example {
public function setstring() {
$this->string = "string";
}
}
So that
$class = new example();
echo $class->string;
Outputs: string
However, in the case that I wanted to create private variables only accessible to functions inside the class, is there anyway to declare them only inside of the setstring() function? Instead of declaring them as private outside of the function like this.
class example {
private $string ='';
public function setstring() {
$this->string = "string";
}
}
The reasons someone might do this are for neatness, so as not to have a long list of private variables declared at the beggining of a class.
No, there is not a way to do that.
In PHP, you typically declare all your class/instance properties above your functions in alphabetical order with self-documenting comments. This is the most "neat" and clear way to write classes. It is also recommended that you avoid public properties entirely, using getters and setters as needed.
The canonical coding style for PHP is defined in PSR-1 and PSR-2. I also recommend that you check out PHPDoc.
Keep in mind, variables declared within the scope of your class method will be private to that method. You only need a class property if you plan to access it from other methods.
<?php
class Example {
/**
* Holds a private string
* #var string
*/
private $string = '';
/**
* Sets the private string variable
*/
public function setString() {
$this->string = 'This string is accessible by other methods';
$privateVar = 'This string is only accessible from within this method';
}
}
Not possible as a language feature, but there's a really simple and effective hack:
class Test
{
/**
* Hidden dynamic data.
* #var object
*/
private $_ = (object)[];
public function setString()
{
$this->_->string = "string";
}
}
You can change $_ into whatever you want, but it does look more hacky to me. $this->this is also an option.
How to create private variables in a PHP Class using OOP
(Object Oriented Programming).
The best way to declare a private variable in a PHP Class is to create them above the __Construction method, by convention you may start the variable with an underscore after the dollar sign (i.e $_private_variable) to let other programmers reading your codes know at sight that it is a private variable, brilliant!
Please declare all your variable in a class as private except the __getter and __setter which are always public, unless you have a reason not to do so.
Use the __setter (__set) function to set value(s) to your private variable inside a the class, and when the value is needed, use the __getter (__get) function to return the values.
To make sense of it, let' create a very small Class that could be use to create different type of Vehicles, this will give you and insight on how to properly create private variable, set values to it and return values from it, ready?
<?php
Class Vehicle{
/* Delcaration of private variables */
private $_name = "Default Vehicle";
private $_model;
private $_type;
private $_identification;
/* Declaration of private arrays */
private $_mode = array();
private $feature = array();
/* Magic code entry function, think of it as a main() in C/C++ */
public function __construct( $name, $model, $type ){
$this->create_vehicle( $name, $model, $type );
}
/* __getter function */
public function __get( $variable ){
if( !empty($this->$variable) ){
$get_variable = $this->$variable;
}
return $get_variable;
}
/* __setter function */
public function __set( $variable, $target ){
$this->$variable = $target;
}
/* Private function */
private function create_vehicle( $name, $model, $type ){
$this->__set( "_name", $name );
$this->__set( "_model", $model);
$this->__set( "_type", $type );
}
}
//end of the class.
?>
<?php
/* Using the Vehicle class to create a vehicle by passing
three parameters 'vehicle name', 'vehicle model', 'vehicle type'
to the class.
*/
$toyota = new Vehicle("Toyotal 101", "TY101", "Sedan");
/* Get the name and store it in a variable for later use */
$vehicle_name = $toyota->__get('_name');
/* Set the vehicle mode or status */
$vehicle_mode = array(
'gas' => 50,
'ignition' => 'OFF',
'tire' => "OK",
'year' => 2020,
'mfg' => 'Toyoda',
'condition' => 'New'
);
/* Create vehicle features */
$vehicle_feature = array(
"Tire" => 4,
"Horse Power" => "V6",
"blah blah" => "foo",
"Airbag" => 2,
"Transmission" => "Automatic"
//....
);
/* Create vehicle identification */
$vehicle_identification = array(
"VIN" => "0001234567ABCD89",
"NAME" => $vehicle_name,
"FEATURE" => $vehicle_feature,
"MODEL" => $vehicle_mode,
"YEAR" => 2020,
"MFG" => "Totota"
);
/* Set vehicle identification */
$toyota->__set("_identification", $vehicle_identification );
/* Set vehicle features */
$toyota->__set("_feature", $vehicle_feature );
/* Set vehicle mode */
$toyota->__set("_mode", $vehicle_mode);
/* Retrieve information and store them in variable using __get (getter) */
$vehicle_name = $toyota->__get('_name');
$vehicle_mode = $toyota->__get('_mode');
$vehicle_id = $toyota->__get('_identification');
$vehicle_features = $toyota->__get('_feature');
$vehicle_type = $toyota->__get('_type');
$vehicle_model = $toyota->__get('_model');
/* Printing information using store values in the variables. */
echo "Printing Vehicle Information\n";
echo "*****************************\n";
echo "Vehicle name is $vehicle_name \n";
echo "Vehicle Model is $vehicle_model \n";
echo "Vehich type is $vehicle_type \n";
printf("\n\n");
echo "Printing Vehicle Mode\n";
echo "***********************\n";
print_r( $vehicle_mode );
printf("\n\n");
echo "Printing Vehicle Features\n";
echo "**************************\n";
print_r( $vehicle_features );
printf("\n\n");
echo "Printing Vehicle Identification\n";
echo "******************************\n";
print_r( $vehicle_id );
printf("\n\n");
?>
The output of this code:
Printing Vehicle Information
*****************************
Vehicle name is Toyotal 101
Vehicle Model is TY101
Vehich type is Sedan
Printing Vehicle Mode
***********************
Array
(
[gas] => 50
[ignition] => OFF
[tire] => OK
[year] => 2020
[mfg] => Toyoda
[condition] => New
)
Printing Vehicle Features
**************************
Array
(
[Tire] => 4
[Horse Power] => V6
[blah blah] => foo
[Airbag] => 2
[Transmission] => Automatic
)
Printing Vehicle Identification
******************************
Array
(
[VIN] => 0001234567ABCD89
[NAME] => Toyotal 101
[FEATURE] => Array
(
[Tire] => 4
[Horse Power] => V6
[blah blah] => foo
[Airbag] => 2
[Transmission] => Automatic
)
[MODEL] => Array
(
[gas] => 50
[ignition] => OFF
[tire] => OK
[year] => 2020
[mfg] => Toyoda
[condition] => New
)
[YEAR] => 2020
[MFG] => Totota
)
To do a live test or experiment with this code, see the demo, change name, create new vehicle(s) as pleased.
I hope this helps.

PDO::FETCH_CLASS Arguments

It's possible to create another instance to send as parameters on the current instance in PDO::fetchAll()?
if \PDO::FETCH_PROPS_LATE is set it will FIRSTLY call the __construct and SECONDLY set the properties. so the values you have passed to the __construct via the array will be overwritten.
But, when it overwritte the values, it doesn't understand the Voucher instance.
It is better illustrate
e.g.
<?php
class Voucher {
private $CD_ID, $CD_VOUCHER, $NR_EXPIRATION, $DT_VOUCHER, $IE_STATUS;
public function __construct($CD_ID, $CD_VOUCHER, $NR_EXPIRATION, $DT_VOUCHER, $IE_STATUS) {
$this->CD_ID = $CD_ID;
$this->CD_VOUCHER = $CD_VOUCHER;
$this->NR_EXPIRATION = $NR_EXPIRATION;
$this->DT_VOUCHER = $DT_VOUCHER;
$this->IE_STATUS = $IE_STATUS;
}
}
class Authentication {
private $CD_AUTH, $DT_AUTH, Voucher $CD_VOUCHER, $CD_IP, $CD_MAC, $CD_LOG;
public function __construct($CD_AUTH, $DT_AUTH, Voucher $CD_VOUCHER, $CD_IP, $CD_MAC, $CD_LOG) {
$this->CD_AUTH = $CD_AUTH;
$this->DT_AUTH = $DT_AUTH;
$this->CD_VOUCHER = $CD_VOUCHER;
$this->CD_IP = $CD_IP;
$this->CD_MAC = $CD_MAC;
$this->CD_LOG = $CD_LOG;
}
}
public function getAuthentications() {
try {
$sth = $this->db->prepare("SELECT `TB_AUTENTICACAO`.`CD_AUTH`, `TB_AUTENTICACAO`.`DT_AUTH`, `TB_VOUCHER`.`CD_ID`, `TB_VOUCHER`.`CD_VOUCHER`, `TB_VOUCHER`.`NR_EXPIRATION`, `TB_VOUCHER`.`DT_VOUCHER`, `TB_VOUCHER`.`IE_STATUS`, `TB_AUTENTICACAO`.`CD_IP`, `TB_AUTENTICACAO`.`CD_MAC`, `TB_AUTENTICACAO`.`CD_LOG` FROM `TB_AUTENTICACAO` INNER JOIN `TB_VOUCHER` ON `TB_VOUCHER`.`CD_ID` = `TB_AUTENTICACAO`.`CD_VOUCHER`;");
$sth->execute();
return $sth->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, "Models\\Authentication", array("TB_AUTENTICACAO.CD_AUTH", "TB_AUTENTICACAO.DT_AUTH", new \Models\Voucher("TB_VOUCHER.CD_ID", "TB_VOUCHER.CD_VOUCHER", "TB_VOUCHER.NR_EXPIRATION", "TB_VOUCHER.DT_VOUCHER", "TB_VOUCHER.IE_STATUS"), "TB_AUTENTICACAO.CD_IP", "TB_AUTENTICACAO.CD_MAC", "TB_AUTENTICACAO.CD_LOG"));
} catch (Exception $exc) {
die($exc->getMessage());
}
}
The result must be:
e.g.
Models\Authentication Object (
[CD_AUTH:Models\Authentication:private] => 2
[DT_AUTH:Models\Authentication:private] => 2016-03-22 10:44:00
[CD_VOUCHER:Models\Authentication:private] => Models\Voucher Object (
[CD_ID:Models\Voucher:private] => 1
[CD_VOUCHER:Models\Voucher:private] => xYgPB5
[NR_EXPIRATION:Models\Voucher:private] => 720
[DT_VOUCHER:Models\Voucher:private] => 2016-03-18 17:00:00
[IE_STATUS:Models\Voucher:private] => 0
)
[CD_IP:Models\Authentication:private] => 10.10.10.10
[CD_MAC:Models\Authentication:private] => abc
[CD_LOG:Models\Authentication:private] => 1
)
but I get:
e.g.
Models\Authentication Object (
[CD_AUTH:Models\Authentication:private] => 2
[DT_AUTH:Models\Authentication:private] => 2016-03-22 10:44:00
[CD_VOUCHER:Models\Authentication:private] => xYgPB5
[CD_IP:Models\Authentication:private] => 10.10.10.10
[CD_MAC:Models\Authentication:private] => abc
[CD_LOG:Models\Authentication:private] => 1
[CD_ID] => 1
[NR_EXPIRATION] => 720
[DT_VOUCHER] => 2016-03-18 17:00:00
[IE_STATUS] => 0
)
I would just keep it simple and define the variable as a class in the class itself. However, I am not sure why you have this issue, perhaps its because you're not attaching a variable to the new class?
If you're using a PHP 5.6+ you can make use of variable-length argument lists.
Seeing your code, I think it will boost read-ability by a-lot but the downside is that you need to make sure the correct number of variables are parsed into the constructor.
class Authentication {
private $CD_AUTH, $DT_AUTH, $CD_VOUCHER, $CD_IP, $CD_MAC, $CD_LOG;
public function __construct($CD_AUTH, $DT_AUTH, array $CD_VOUCHER, $CD_IP, $CD_MAC, $CD_LOG) {
...
$this->CD_VOUCHER = new \Models\Voucher(...$CD_VOUCHER);
...
# or go anonymous in php 7
$this->CD_VOUCHER = new class(...$CD_VOUCHER){
function __construct($CD_ID, $CD_VOUCHER, $NR_EXPIRATION, $DT_VOUCHER, $IE_STATUS){
...
}
}
}
}
public function getAuthentications() {
try {
$sth = $this->db->prepare("...");
$sth->execute();
return $sth->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, "Models\\Authentication", array("TB_AUTENTICACAO.CD_AUTH", "TB_AUTENTICACAO.DT_AUTH", ["TB_VOUCHER.CD_ID", "TB_VOUCHER.CD_VOUCHER", "TB_VOUCHER.NR_EXPIRATION", "TB_VOUCHER.DT_VOUCHER", "TB_VOUCHER.IE_STATUS"], "TB_AUTENTICACAO.CD_IP", "TB_AUTENTICACAO.CD_MAC", "TB_AUTENTICACAO.CD_LOG"));
} catch (Exception $exc) {
die($exc->getMessage());
}
}

PHP SoapClient missing data

I'm using a SoapClient (zend2), but for some reasons, can't get complete data answer
$client = new \SoapClient($host);
$result = $client->getInvoice();
$result var_dump:
["ListInvoiceResult"] => object(stdClass)#282 (4) {
["Status"] => int(1)
["ErrorCode"] => NULL
["ErrorMessage"] => string(0) ""
["Invoice"] => array(1436) {
[0] => object(stdClass)#283 (3) {
["ID"] => int(12741)
["Date"] => string(10) "2011.01.31"
["DateSales"] => string(10) "2011.01.31"
}
Above object missing a variable InvoiceNumber
But when I call __getLastResponse method , I've recieved complete data with InvoiceNumber
<p1:Invoice>
<p1:ID>12741</p1:ID>
<p1:InvoiceNumber>1|FA|2011|00633</p1:InvoiceNumber>
<p1:Date>2011.01.31</p1:Date>
<p1:DateSales>2011.01.31</p1:DateSales>
</p1:Invoice>
Hmmm. Looks strange. But all other methods returns complete data, even variable Invoice Number..
I think you should try using the classmap option in SoapClient or check you mapped classes, for instance:
class MyBook {
public $title;
public $author;
}
$server = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));
In your case you should model ListInvoiceResult and Invoice class for instance:
class WS_ListInvoiceResult {
public $Status;
public $ErrorCode;
public $ErrorMessage;
public $Invoice;
}
class WS_Invoice {
public $ID;
public $Date;
public $DateSales;
public $InvoiceNumber;
}
And connect to soap api as such:
$server = new SoapClient("wsdl path", array('classmap' => array("ListInvoiceResult" => "WS_ListInvoiceResult", "Invoice" => "WS_Invoice")));
If this doesn't help try checking your WSDL, though based on the response it appears to be OK.

how to save many objects in a $session array variable

I'm new in the object oriented programming so this question might be silly...
I've created my class in a separate file called classProduct.php
<?php
class product{
public $prodId;
public $prodName;
public $prodPrice;
public function __construct($prodId,$prodName,$prodPrice){
$this->prodId = $prodId;
$this->prodName=$prodName;
$this->prodPrice=$prodPrice;
}
public function get_prodId(){
return $this->prodId;
}
public function get_prodName(){
return $this->prodName;
}
public function get_prodPrice(){
return $this->prodPrice;
}
}
?>
Then I tried to create a new object in a $_SESSION variable. This happens in another file called dailySales.php where I include the previous file using:
include_once("classProduct.php");
What I want to do is to save in $_SESSION['myItems'] each new object. I am trying something like:
$newItem= new product($var,$var,$var);
$_SESSION['myItems']=array($newItem); // I believe here is where I do it wrong
Every time the buyer chooses one more products, the pages reloads (with ajax). When I echo or var_dump the $_SESSION['myItems'] I only get the last object. What do I need to change to get it working correctly?
Of course I do need the object so I can easily remove a product from the shopping cart if
'Delete' is pressed.
This is working for me locally.
Define your items session variable as an array, then push them into the variable using array_push
class product {
public $prodId;
public $prodName;
public $prodPrice;
public function __construct($prodId, $prodName, $prodPrice) {
$this->prodId = $prodId;
$this->prodName = $prodName;
$this->prodPrice = $prodPrice;
}
public function get_prodId() {
return $this->prodId;
}
public function get_prodName() {
return $this->prodName;
}
public function get_prodPrice() {
return $this->prodPrice;
}
}
Then use it like so:
$product = new product(1, "test", 23);
$product2 = new product(2, "test2", 43);
$_SESSION['items'] = array();
array_push($_SESSION['items'], $product, $product2);
echo '<pre>';
print_r($_SESSION['items']);
echo '</pre>';
This is the output of print_r()
Array
(
[0] => product Object
(
[prodId] => 1
[prodName] => test
[prodPrice] => 23
)
[1] => product Object
(
[prodId] => 2
[prodName] => test2
[prodPrice] => 43
)
)

PHP object can not access variable

Using the following:
$last_book = tz_books::getLast($request->db, "WHERE book_id='{$request->book_id}'");
I get the following php object array,
[0] => tz_books Object
(
[db:tz_books:private] => com Object
[id] => 64BEC207-CA35-4BD2
[author_id] => 4F4755B4-0CE8-4251
[book_id] => 8FC22AA0-4A60-4BFC
[date_due] => variant Object
)
I then want to use the author_id, but for some reason it's not working.
Trying to use:
$tz_books->author_id;
Using print_r($last_book); prints the array to the console just fine. And Doing the following just to see if the correct variable was being used:
$author = $tz_books->author_id;
print_r($author);
Nothing is printed to the console, and even after digging through the php manual and trying a lot of alternatives, I can't seem to grab that variable. I'm hoping i'm making a rookie mistake and overlooking something stupid. Thank you for any help!
Edit: Class definition
private $db;
public $id;
public $author_id;
public $book_id;
public $date_due;
public function __construct($db, $values=null) {
$this->db = $db;
if ( $values != null ) {
foreach ( $values as $var => $value ) {
$this->$var = $value;
}
}
}
public static function retrieveAll($db, $where='', $order_by='') {
$result_list = array();
$query = 'SELECT '.
'id, '.
'author_id, '.
'book_id, '.
'date_due '.
"FROM tz_books $where $order_by";
$rs = $db->Execute($query);
while ( !$rs->EOF ) {
$result_list[] = new tz_books($db, array(
'id' => clean_id($rs->Fields['id']->Value),
'author_id' => clean_id($rs->Fields['author_id']->Value),
'book_id' => clean_id($rs->Fields['book_id']->Value),
'date_due' => $rs->Fields['date_due']->Value,
));
$rs->MoveNext();
}
$rs->Close();
return $result_list;
}
Your result object seems to be an array of books with 1 element.
Try
echo $tz_books[0]->author_id;
BTW, it also looks like you're escaping input by putting single quotes. This is not a reliable/recommended method. Use a database-specific escape function like this

Categories