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

4
  • 6
    None of those two classes are valid class declarations in the first place Commented Oct 7, 2013 at 5:58
  • 1
    Do you want your productId method to be static? Commented Oct 7, 2013 at 5:58
  • 1
    First step you need to declare public variable inside class. Then use extends to extend the first class in second class to access base class variables Commented Oct 7, 2013 at 6:01
  • You should learn oop first cause you don't know what is it and what is it for so we can't help you. Commented Oct 7, 2013 at 6:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Might help mentioning the mistakes that they had, a number of them
And echo $this->$db; should be echo $this->db;
Good catch, @AmalMurali. Rectified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.