0

i am new to php oop

I have an two files Here is my code

1)info.php

public $bd, $db1;    
class Connection {  
  function connect() {  
    $this->db = 'hello world';  
    $this->db1 = 'hi'  
  }  
}

2) prd.php

require_once 'info.php'
class prdinfo {  
  function productId() {  
    echo Connection::connect()->$bd;  
    echo Connection::connect()->$db1;   
  }  
$prd = new prdinfo ();  
$prd->productId ();  

how i can echo my var in 2nd class i have tried in that way but i am not getting proper output

Thanks

Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
Durgaprasad
  • 157
  • 2
  • 6
  • 19

1 Answers1

3

It should be something like this.

info.php

class Connection {
   // these two variable should be declared within the class.
   protected $db; // to be able to access these variables from a diff class
   protected $db1; // either their scope should be "protected" or define a getter method.

   public function __construct() {
      $this->connect();
   }

   private function connect() {
       $this->db = 'hello world';
       $this->db1 = 'hi';
   }
}

prd.php

require_once 'info.php';

// you are accessing the Connection class in static scope
// which is not the case here.
class prdinfo extends Connection {
   public function __construct() {
       // initialize the parent class
       // which in turn sets the variables.
       parent::__construct();
   }

   public function productId() {
        echo $this->db;
        echo $this->db1;
   }
}


$prd = new prdinfo ();
$prd->productId ();

This is a basic demonstration. Modify it as per your needs. More here - http://www.php.net/manual/en/language.oop5.php

web-nomad
  • 6,003
  • 3
  • 34
  • 49