I
I
iWo2014-07-16 10:49:52
PHP
iWo, 2014-07-16 10:49:52

How to inherit a PHP property?

There is a class connection to the database in the constructor.

class OCIConnect
{
  public $connect = null;
  public function __construct() {
        $this->connect = oci_connect($this->user, $this->pass, $this->dbHost);
        if (!$this->connect) {
            $m = oci_error();
            exit('Ошибка подключения ' . $m['message']);
        }
    }
}

How to use the connect object in another class?
class Agent extends OCIConnect
{
  function __construct()
  {
    parent::__construct();
  }
public static function getData($sql,$bind = null) {
        $query = oci_parse($this->connect, $sql);
    }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey, 2014-07-16
@iWo

Read about encapsulation. And advice - do not do exit or initialization of the connection to the database inside the classes. Lazy initialization is much more convenient.

class OCIConnect
{
  private $link = null;
  public function __construct($user, $pass, $host) {
        // fixme: это не стоит делать в конструкторе, лучше использовать ленивую инициализацию.
        $this->link = oci_connect($user, $pass, $dbHost);
        if (!$this->connect) {
            $m = oci_error();
            throw new Exception(sprintf('Connection error: %s', $m['message']));
        }
    }

    public function exec($sql) 
    {
         // exec sql
    }
}

class Agent
{
        /**
        * @var $connection
        **/
        private $connection;

  function __construct(OCIConnect $connection)
  {
               $this->connection = $connection;
  }
        public static function getData($sql,$bind = null) {
                // do something
               $this->connection->exec($sql);
        }
}

P
Push Pull, 2014-07-16
@deadbyelpy

Those. you want to say that
this code does not work?
In the inherited class, all properties are visible except private.

public static function getData($sql,$bind = null) {
        $query = oci_parse($this->connect, $sql);
    }

E
Evgeny Komarov, 2014-07-16
@maNULL

If you want to access the $connect property of the parent class from the child class, then just as you did with the parent::$connect constructor of the child class; And try to wean yourself from the abundance of unnecessary public properties.

A
Alexander, 2014-07-16
@SashaSkot

parent:: connect
and in general OOP in Pehape strongly beats on productivity. Today it is a utopia.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question