Php fatal error cannot use object of type stdclass as array in

I get a strange error using json_decode(). It decode correctly the data (I saw it using print_r), but when I try to access to info inside the array I get: Fatal error: Cannot use object of type st...

instead of using the brackets use the object operator for example my array based on database object is created like this in a class called DB:

class DB {
private static $_instance = null;
private $_pdo,
        $_query, 
        $_error = false,
        $_results,
        $_count = 0;



private function __construct() {
    try{
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') .';dbname=' . Config::get('mysql/db') , Config::get('mysql/username') ,Config::get('mysql/password') );


    } catch(PDOException $e) {
        $this->_error = true;
        $newsMessage = 'Sorry.  Database is off line';
        $pagetitle = 'Teknikal Tim - Database Error';
        $pagedescription = 'Teknikal Tim Database Error page';
        include_once 'dbdown.html.php';
        exit;
    }
    $headerinc = 'header.html.php';
}

public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }

    return self::$_instance;

}


    public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
    $x = 1;
        if(count($params)) {
        foreach($params as $param){
            $this->_query->bindValue($x, $param);
            $x++;
            }
        }
    }
    if($this->_query->execute()) {

        $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
        $this->_count = $this->_query->rowCount();

    }

    else{
        $this->_error = true;
    }

    return $this;
}

public function action($action, $table, $where = array()) {
    if(count($where) ===3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} = ?";

            if(!$this->query($sql, array($value))->error()) {
            return $this;
            }
        }

    }
    return false;
}

    public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);

public function results() {
    return $this->_results;
}

public function first() {
    return $this->_results[0];
}

public function count() {
    return $this->_count;
}

}

to access the information I use this code on the controller script:

<?php
$pagetitle = 'Teknikal Tim - Service Call Reservation';
$pagedescription = 'Teknikal Tim Sevice Call Reservation Page';
require_once $_SERVER['DOCUMENT_ROOT'] .'/core/init.php';
$newsMessage = 'temp message';

$servicecallsdb = DB::getInstance()->get('tt_service_calls', array('UserID',
 '=','$_SESSION['UserID']));

if(!$servicecallsdb) {
// $servicecalls[] = array('ID'=>'','ServiceCallDescription'=>'No Service Calls');
} else {
$servicecalls = $servicecallsdb->results();
}
include 'servicecalls.html.php';



?>

then to display the information I check to see if servicecalls has been set and has a count greater than 0 remember it’s not an array I am referencing so I access the records with the object operator «->» like this:

<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/header.html.php';?>
<!--Main content-->
<div id="mainholder"> <!-- div so that page footer can have a minum height from the
  header -->
<h1><?php if(isset($pagetitle)) htmlout($pagetitle);?></h1>
<br>
<br>
<article>
    <h2></h2>
</article>
<?php
if (isset($servicecalls)) {
if (count ($servicecalls) > 0){
     foreach ($servicecalls as $servicecall) {
        echo '<a href="/servicecalls/?servicecall=' .$servicecall->ID .'">'
  .$servicecall->ServiceCallDescription .'</a>';
    }
}else echo 'No service Calls';

}

?>
<a href="/servicecalls/?new=true">Raise New Service Call</a>
</div> <!-- Main content end-->
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/footer.html.php'; ?>

The given snippet is dedicated to a common PHP issue «cannot use object of Type stdClass as an array».

Read on to learn how to fix this issue accurately.

The function that we recommend you to use is json_decode.

This function is capable of returning an object by default.

Data may be accessed in the following way:

var_dump($result->context);

In the event of having identifiers such as, you should implement:

var_dump($result->{'from-date'});

In case you intend to have an array, then run the code below:

$result = json_decode($json, true);

Alternatively, you can cast the object to an array like so:

$result = (array) json_decode($json);

Let’s consider another solution with the -> sign.

So, access with the help of -> as it is an object.

Then, change the code from:

To:

There you are.

This is considered an empty class in PHP. It is applied for casting other types to the object. The stdClass has similarities with Python or Java objects.

You should take into consideration that stdClass is not the base class. Once an object is converted to an object, it is not changed. Yet, once an object type is converted to an instance of the stdClass generated, it is not NULL. Once it is NULL, the new instance will be empty.

The main use cases of the stdClass in PHP are:

  • It directly accesses the members by calling them.
  • It is handy for dynamic objects.
  • It is used for setting dynamic properties, and so on.

The json_decode function is used for taking a JSON encoded string and converting it into a PHP variable.

It has four parameters: json, assoc, depth, and options.

Once the assoc parameter is TRUE, then the returned objects will be converted to associative arrays.

How many times have you fallen upon the dreaded “cannot use object of type stdClass as array” error message? In this tutorial, you will learn how to solve the error and it’s much easier than you think.

The PHP engine throws the “cannot use object of type stdClass as array” error message due to your code trying to access a variable that is an object type as an array. It is most likely that you’ve tried to access the data with the generic bracket array accessor and not an object operator. Always ensure that you know the variable type before you try to access the data.

See the following example which will throw this error.

Example code 1 (Throws error)

This example shows an object being accessed with an array style syntax which, throws an error of “cannot use object of type stdClass as array”

PHP

$object = new stdClass();
$object->myFirstProperty = 'My First Value';
$object->mySecondProperty = 'My Second Value';
$object->myThirdProperty = 'My Third Value';
$object->myFourthProperty = 'My Fourth Value';


echo $object["myFirstProperty"]; // Error thrown here

And the second example that won’t throw an error.

Example code 2 (Doesn’t throw an error)

Using the same code whilst using the object operator to access the values will not throw the error.

PHP

$object = new stdClass();
$object->myFirstProperty = 'My First Value';
$object->mySecondProperty = 'My Second Value';
$object->myThirdProperty = 'My Third Value';
$object->myFourthProperty = 'My Fourth Value';


//echo $object["myFirstProperty"];

echo $object->myFirstProperty;

Output

My First Value

So how do we get around the error

There are two choices to solve the issue of this error.

  1. Access the values with an object operator as demonstrated in Code Example 2.
  2. Convert the object to an array before accessing it with array style syntax (Example below)

Example code 3 (Doesn’t throw an error)

$object = new stdClass();
$object->myFirstProperty = 'My First Value';
$object->mySecondProperty = 'My Second Value';
$object->myThirdProperty = 'My Third Value';
$object->myFourthProperty = 'My Fourth Value';

$array = json_decode(json_encode($object), true);


echo $array["myFirstProperty"];

Output

My First Value

Summary

And that is all there is to it, it is simple, yes, but you can be caught out when using the various frameworks such as Laravel. Laravel returns database data via the eloquent library it uses as an object by default and so it must be converted to an array to prevent the error from being thrown. Check out an article I wrote previously on converting an object to an array in PHP.

Suddenly, one day you get into trouble with the fatal error “Cannot use object of type stdclass as array”. And you are also looking for a useful solution to handle this problem. Luckily, in this blog, we are going to explain and fix this common error that every programmer face. Before going over the solutions, you need to understand why this error arises.

Why did you hit the error “cannot use object of type stdclass as array”?

The error “cannot use object of type stdclass as array’ occurs. Because once you utilize
json_decode();
function, it returns an object of type stdClass. Whereas, the arguments which are to be passed inside of
print_r()
should either be a string or an array. Therefore, once you pass an object inside of
print_r()
, then this error will come in PHP.

Now, let’s refer to the following solution to handle this problem.

Cannot Use Object Of Type Stdclass As Array

How to tackle fatal error “Cannot use object of type stdClass as array” in php

Here are the two solutions that can help you resolve your issue:

Method 1: Cast the object to an array

Now, you need to cast the object to an array as below:


$a = (array)$object;

Method 2: By accessing the key of the Object

As we revealed above, once you utilize
json_decode();
function, you will get an Object of stdClass as return type. So, you are able to access the elements of the object thanks to the assistance of
->
Operator.

You need to implement as follows:


$value = $object->key;

In case the object has plenty of nested arrays, you can also utilize different keys to extract the sub-elements. For example:


$value = $object->key1->key2->key3...;

Alternatively, you also set the change the second parameter of the
json_decode();
to true, then the object will be automatically converted to an
array();
.

Also, If you set the second parameter of the json_decode(); to true, it will automatically convert the object to an
array();
.

Wrap up

Has your error been resolved? If yes, let us know the solution that is useful for your error by leaving a comment below. In case, your error is not disappearing, don’t hesitate to share with us your situation. We are always willing to support you.

Last but not least, our website specializes in providing plenty of stunning, SEO-friendly free WordPress themes. You can visit and get one to make your site more appealing. Thanks for your reading.

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)

PROBLEM :

We get a strange error using json_decode(). It decode correctly the data, but when we try to access info inside the array we get the following:

[pastacode lang=”php” manual=”Fatal%20error%3A%20Cannot%20use%20object%20of%20type%20stdClass%20as%20array%20in%0AC%3A%5CUsers%5CWiki%5Csoftware%5Cwikitechy.php%20on%20line%20108%0A” message=”Php Code” highlight=”” provider=”manual”/]

We tried to do: $result[‘context’] where $result has the data returned by json_decode()

php json

SOLUTION 1:

The function json_decode() returns an object by default.

Access the data :

[pastacode lang=”php” manual=”var_dump(%24result-%3Econtext)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

If we have identifiers like from-date (the hyphen would cause a PHP error when using the above method) we have to write the following:

[pastacode lang=”php” manual=”var_dump(%24result-%3E%7B’from-date’%7D)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

  • If we have identifiers like from-date (the hyphen would cause a PHP error when using the above method) we have to write the following:

[pastacode lang=”php” manual=”var_dump(%24result-%3E%7B’from-date’%7D)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

  • If we need an array we can do the following:

[pastacode lang=”php” manual=”%24result%20%3D%20json_decode(%24json%2C%20true)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

  • Or cast the object to an array:

[pastacode lang=”php” manual=”%24result%20%3D%20(array)%20json_decode(%24json)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

SOLUTION 2:

  • Use the second parameter of json_decode to make it return an array:

[pastacode lang=”php” manual=”%24result%20%3D%20json_decode(%24data%2C%20true)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

SOLUTION 3:

  • Use true as the second parameter to json_decode.
  • This will decode the json into an associative array instead of stdObject instances:

[pastacode lang=”php” manual=”%24my_array%20%3D%20json_decode(%24my_json%2C%20true)%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

SOLUTION 4:

  • If we call json_decode($somestring) we will get an Object and we need to access like $object->key,
  • But if we call json_decode($somestring, true) we will get an array and can access like $array[‘key’]

SOLUTION 5:

We can convert stdClass object to array :

[pastacode lang=”php” manual=”%24array%20%3D%20(array)%24stdClass%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

SOLUTION 6:

function:

[pastacode lang=”php” manual=”mixed%20json_decode%20(%20string%20%24json%20%5B%2C%20bool%20%24assoc%20%3D%20false%20%5B%2C%20int%20%24depth%20%3D%20512%20%5B%2C%20int%20%24options%20%3D%200%20%5D%5D%5D%20)%0A” message=”Php Code” highlight=”” provider=”manual”/]

  • When param is false, which is default, it will return an appropriate php type.
  • When param is true, it will return associative arrays.
  • It will return NULL on error.
  • If we want to fetch value through array, set assoc to true.

SOLUTION 7:

we must access it using -> since its an object.

Change our code from:

[pastacode lang=”php” manual=”%24result%5B’context’%5D%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

To:

[pastacode lang=”php” manual=”%24result-%3Econtext%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

SOLUTION 8:

  • print_r — Prints human-readable information about a variable
  • When we use json_decode();, we get an object of type stdClass as return type.
  • The arguments, which are to be passed inside of print_r() should either be an array or a string. Hence, we cannot pass an object inside of print_r(). There are two ways to deal with this.

1. Cast the object to array.
This can be achieved as follows.

[pastacode lang=”php” manual=”%24a%20%3D%20(array)%24object%3B%0A” message=”php Code” highlight=”” provider=”manual”/]

2. By accessing the key of the Object
when we use json_decode(); function, it returns an Object of stdClass. we can access the elements of the object with the help of -> Operator.

[pastacode lang=”php” manual=”%24value%20%3D%20%24object-%3Ekey%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

  • Use multiple keys to extract the sub elements incase if the object has nested arrays.

[pastacode lang=”php” manual=”%24value%20%3D%20%24object-%3Ekey1-%3Ekey2-%3Ekey3…%3B%0A” message=”Php Code” highlight=”” provider=”manual”/]

Their are many options to print_r() like var_dump(); and var_export();

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I’m a frequent speaker at tech conferences and events.

Related Tags
  • Cannot use object of type stdClass as array,
  • Cannot use object of type stdClass as array – JSON,
  • Cannot use object of type stdClass as array in,
  • Cannot use object of type stdClass as array magento,
  • Cannot use object of type stdClass as array(php),
  • JSON Decode Fatal error: Cannot use object of type stdClass as array in,
  • json_decode to array,
  • php,
  • php — Cannot use object of type stdClass as array,
  • What is the correct JSON content type?

Stdclass is a Standard Defined Classes. Stdclass is a generic empty class created by PHP. PHP uses this class when casting.

It is just a predefined class like Object in Java. It’s not the base class of the objects.


  • Is stdClass the base class of the objects?
  • Why does it throw an PHP Fatal error ‘cannot use an object of type stdclass as array’ and How to fix this error?
  • Ways to Convert stdclass object to an associative array in php?
  • How to fix stdclass undefined property error?
  • Learn about Stdclass object Php foreach loop with Examples
  • Feedback: Your input is valuable to us. Please provide feedback on this article.

No.

StdClass is NOT the Base class of the object. Let’s see with below example

 
class abc {}

$object = new abc();

if ($object instanceof stdClass) {
    echo 'Yes! It is';
} else {
     echo 'No, StdClass is NOT Base class of the object';
}

//Output: 'No, StdClass is NOT Base class of the object

Why did it happen? Answer is in Question too that our code is trying to access values as array even though it was object type.

Solution: Just change of accessing value from generic bracket like
$array[‘name_of_param’] To $array->name_of_param.

Let’s understand through example:

Throw Error:

 
// Throw Error:

$array =  array(
        'name' => 'demo',
        'age' => '21',
        'address' => '123, wall street'
    
);



$object = (object) $array;

echo $object instanceof stdClass ? "Yes" : "No";

// Output : Yes

//Trying to access as array
 echo $object['name'];
   // Throws : PHP Fatal error:  Uncaught Error: Cannot use object of type stdClass as array ....
   

Successfully access value using object access operator

 

$array =  array(
        'name' => 'demo',
        'age' => '21',
        'address' => '123, wall street'
    
);



$object = (object) $array;

echo $object instanceof stdClass ? "Yes" : "No";

// Output : Yes

 echo $object->name;

//Output: demo

We can convert into array from stdclass in following ways:

Convert stdclass to associative array using json_decode

<?php


$stdObj = new stdClass();
$stdObj->name = "Demo";
$stdObj->age = 20;


$array = json_decode(json_encode($stdObj), true);
// Json decode with second argumen true will return associative arrays.

print_r($array);
//Output Array ( [name] => Demo [age] => 20 )  

Typecasting

Simple objects can convert using (array) typecasting.

Example: $array = (array) $stdObj;

Complex objects or lists of objects are converted into a multidimensional array by looping through each single object with typecasting.

stdclass undefined property error reported when we try to access property which does not exist/declared. It’s best practise to check whether a property is set or not. We can use the php inbuilt function isset() for such cases.

Let see with below example

Why stdclass undefined property issue? Let’s see with this example

$stdObj = new stdClass();
$stdObj->name = "Demo";
$stdObj->age = 20;

echo $stdObj->notExist;

// Will throw error : PHP Notice:  Undefined property: stdClass::$notExist

Fix stdclass undefined property issue

$stdObj = new stdClass();
$stdObj->name = "Demo";
$stdObj->age = 20;

echo isset($stdObj->notExist) ? "Property notExist is defined" : "Property notExist is NOT defined";

// Property notExist is NOT defined

Fetching values from stdclass object depends on object type. We don’t need looping for single dimensional object. We can fetch values like $obj->param.

We require looping through objects which is multidimensional or complex structure. Please check Stdclass object Php foreach loop
for well explained about stdclass object looping with easy to understand examples.

Yes, it was beneficial.

Yes, it was helpful, however more information is required.

It wasn’t helpful, so no.

Feedback (optional) Please provide additional details about the selection you chose above so that we can analyze the insightful comments and ideas and take the necessary steps for this topic. Thank you

Send Feedback

instead of using the brackets use the object operator for example my array based on database object is created like this in a class called DB:

class DB {
private static $_instance = null;
private $_pdo,
        $_query, 
        $_error = false,
        $_results,
        $_count = 0;



private function __construct() {
    try{
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') .';dbname=' . Config::get('mysql/db') , Config::get('mysql/username') ,Config::get('mysql/password') );


    } catch(PDOException $e) {
        $this->_error = true;
        $newsMessage = 'Sorry.  Database is off line';
        $pagetitle = 'Teknikal Tim - Database Error';
        $pagedescription = 'Teknikal Tim Database Error page';
        include_once 'dbdown.html.php';
        exit;
    }
    $headerinc = 'header.html.php';
}

public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }

    return self::$_instance;

}


    public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
    $x = 1;
        if(count($params)) {
        foreach($params as $param){
            $this->_query->bindValue($x, $param);
            $x++;
            }
        }
    }
    if($this->_query->execute()) {

        $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
        $this->_count = $this->_query->rowCount();

    }

    else{
        $this->_error = true;
    }

    return $this;
}

public function action($action, $table, $where = array()) {
    if(count($where) ===3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} = ?";

            if(!$this->query($sql, array($value))->error()) {
            return $this;
            }
        }

    }
    return false;
}

    public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);

public function results() {
    return $this->_results;
}

public function first() {
    return $this->_results[0];
}

public function count() {
    return $this->_count;
}

}

to access the information I use this code on the controller script:

<?php
$pagetitle = 'Teknikal Tim - Service Call Reservation';
$pagedescription = 'Teknikal Tim Sevice Call Reservation Page';
require_once $_SERVER['DOCUMENT_ROOT'] .'/core/init.php';
$newsMessage = 'temp message';

$servicecallsdb = DB::getInstance()->get('tt_service_calls', array('UserID',
 '=','$_SESSION['UserID']));

if(!$servicecallsdb) {
// $servicecalls[] = array('ID'=>'','ServiceCallDescription'=>'No Service Calls');
} else {
$servicecalls = $servicecallsdb->results();
}
include 'servicecalls.html.php';



?>

then to display the information I check to see if servicecalls has been set and has a count greater than 0 remember it’s not an array I am referencing so I access the records with the object operator «->» like this:

<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/header.html.php';?>
<!--Main content-->
<div id="mainholder"> <!-- div so that page footer can have a minum height from the
  header -->
<h1><?php if(isset($pagetitle)) htmlout($pagetitle);?></h1>
<br>
<br>
<article>
    <h2></h2>
</article>
<?php
if (isset($servicecalls)) {
if (count ($servicecalls) > 0){
     foreach ($servicecalls as $servicecall) {
        echo '<a href="/servicecalls/?servicecall=' .$servicecall->ID .'">'
  .$servicecall->ServiceCallDescription .'</a>';
    }
}else echo 'No service Calls';

}

?>
<a href="/servicecalls/?new=true">Raise New Service Call</a>
</div> <!-- Main content end-->
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/footer.html.php'; ?>

  1. shabbir

    shabbir
    Administrator
    Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,370
    Likes Received:
    387
    Trophy Points:
    83

    Working in WordPress I wanted to check the type of page. I.e. is the content type as page or post. I used the global $post WordPress variable and when I did variable dump for the object using print_r.

    echo '<pre>';print_r($post);echo'</pre>';

    I got

        [post_title] => Hello world!
        [post_excerpt] => Small Description about the post.
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] => 
        [post_name] => hello-world
        [to_ping] => 
        [pinged] => 
        [post_modified] => 2011-03-12 13:57:23
        [post_modified_gmt] => 2011-03-12 13:57:23
        [post_content_filtered] => 
        [post_parent] => 0
        [guid] => Post URI
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] => 
        [comment_count] => 0
        [ancestors] => Array
            (
            )
     
        [filter] => raw
    

    So when I tried using as $post[‘post_type’] I got the following error.

    Fatal error: Cannot use object of type stdClass as array

    Searching online I found lot of solutions that talk about Upgrading PHP as well as doing ini settings change. I was sure that I am not going to do anything of that sort and finally I found that $post is an object and not an array and so you should access it like

    and notI hope this helps lot of fellow WordPress Developer’s

  2. Assalamu alikum,
    Dear Brother,
    This is mohideen form chennai in tamilnadu.
    am having 2 dout .plz clear this problems
    1) how to create the single excel database….( plz tell me step wise)

    2)how to hack the another pc in command promt way ( plz tell me step wise)

    an trying to below way .but it is failier.

    first am typing net user then press enter key
    then am tracert gmail.com.pc showing some ip’s. am choosing first ip
    then am doing ping that ip
    reply is success.
    i dont no after commond and process …
    plz help me


  3. bhavanaets

    bhavanaets
    Banned

    Joined:
    Apr 8, 2011
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0

    when i echo it, it didn’t show anything,
    echo $response;then i thought, maybe its an array so i put this code:
    echo «<pre>»;
    var_dump($response);
    echo «</pre>»;it worked, i got these results on my browser: OUTPUT:
    object(stdClass)#6 (9) {
    [«Timestamp»]=>
    string(20) «2007-07-18T04:50:52Z»
    [«Ack»]=>
    string(7) «Success»
    [«CorrelationID»]=>
    string(13) «28c01821ba2c2»
    [«Version»]=>
    string(8) «2.400000»
    [«Build»]=>
    string(6) «1.0006»
    [«Amount»]=>
    object(stdClass)#7 (2) {
    [«_»]=>
    string(5) «40.00»
    [«currencyID»]=>
    string(3) «USD»
    }
    [«AVSCode»]=>
    string(1) «X»
    [«CVV2Code»]=>
    string(1) «M»
    [«TransactionID»]=>
    string(17) «14E028078XJ827961UX»
    }
    ok, i didn’t want to show this to my users, instead, i wanted to show only the TransactionID part so i put this code instead:
    echo $response[‘TransactionID’][17];
    that’s when i got this error:
    Fatal error: Cannot use object of type stdClass as array in C:windows-htdocs-cart.php on line 535
    ok, so how do you fix this error,i looked it up on google and found some post and forums where it say to upgrade my php or change the softwar or that i have a bad script. well, i finally figured out. it turns out that $response is actually an object. i have no idea what are objects in PHP but i came across an article about ojects and i found out that if you want to display it or show it with echo or print, you actually have to use the a different format. so in my example above, if i wanted to show the value TransactionID, this is how i would do it:

    CODE
    echo $response->TransactionID;
    OUTPUT:
    14E028078XJ827961UX

Share This Page


Go4Expert

Понравилась статья? Поделить с друзьями:
  • Php fatal error call to undefined function curl init
  • Pip install jupiter notebook error
  • Php fatal error allowed memory size of 2147483648 bytes exhausted tried to allocate 20480 bytes
  • Pip install hashlib error
  • Php fatal error allowed memory size of 134217728 bytes exhausted tried to allocate 36864 bytes