Home > Mobile >  Uncaught Error: Object of class CompanyName could not be converted to string
Uncaught Error: Object of class CompanyName could not be converted to string

Time:04-27

I have two classes in PHP.

  1. RequestorId.php
<?php

class RequestorId
{

    /**
     * @var CompanyName $CompanyName
     * @access public
     */
    public $CompanyName = null;

    /**
     * @var string $ID
     * @access public
     */
    public $ID = null;

    /**
     * @var string $ID_Context
     * @access public
     */
    public $ID_Context = null;

    /**
     * @param CompanyName $CompanyName
     * @param string $ID
     * @param string $ID_Context
     * @access public 
     * **/
    public function __construct($CompanyName, $ID, $ID_Context)
    {
      $this->$CompanyName = $CompanyName;
      $this->$ID = $ID;
      $this->$ID_Context = $ID_Context;
    }

}
  1. CompanyName.php
<?php

class CompanyName
{

    /**
     * @var string $Code
     * @access public
     */
    public $Code = null;

    /**
     * @param string $Code
     * @access public
     */
    public function __construct($Code)
    {
      $this->Code = $Code;
    }

}

I received this error "Uncaught Error: Object of class CompanyName could not be converted to string", when I use them like this:

    $companyname = new CompanyName('SampleName');
    $requestorid = new RequestorId($companyname, '10', 'sss'); <<-- error happen here

Can anyone help me and point me in the right direction, please?

CodePudding user response:

It's a typo in your RequestorId constructor class. Rewrite it like this:

public function __construct($CompanyName, $ID, $ID_Context)
    {
      $this->CompanyName = $CompanyName;
      $this->ID = $ID;
      $this->ID_Context = $ID_Context;
    }

You must remove $ sign from the beginning of properties when accessing them.

When you use $ in front of CompanyName it means that you want to have a dynamic property name based on what is the value of $CompanyName provided in constructor. Then php tries to convert your class to string but it can't and you get the error.

  •  Tags:  
  • php
  • Related