PHP extending class properties

I have two classes in a PHP application, B, for example extension A. Class A has a function that returns some of its other properties as an array of SQL insert queries, for example

Class A {
$property_a;
$property_b;
$property_c;
$property_d;

function queries() {
$queries = array();
$queries[] = "INSERT INTO xxx VALUES " . $this->property_a . ", " . $this->property_b";
$queries[] = "INSERT INTO yyy VALUES " . $this->property_b . ", " . $this->property_d";
}
}

      

I would like class B to have a similar (identical) function that does the same for the properties of class B while keeping the values โ€‹โ€‹from class A. The idea is that every request will be passed through a final function all at the same time :

$mysqli->query("START TRANSACTION");
foreach($queries as $query) {
if(!$mysqli($query)) {
$mysqli->rollback();
}
}

      

IF everything is OK $ mysqli-> commit ();

What would be the easiest way to achieve this? Any tips and ideas. Thank!

+2


source to share


4 answers


Inside B :: queries (), you can call the parent implementation of this method and add your data to the array a :: queries () returns.

class B extends A {
  protected $property_e=5;
  public function queries() {
    $queries = parent::queries();
    // In a real application property_e needs to be sanitized/escaped
    // before being mixed into the sql statement.
    $queries[] = "INSERT INTO zzz VALUES " . $this->property_e;
    return $queries;
  }
}
$b = new B;
foreach( $b->queries() as $q ) {
  echo $q, "\n";
}

      



But you may (also) want to look into the ORM library, for example for example. doctrine .

+4


source


Use getter function to grab properties in requests (). In each class, you can control what values โ€‹โ€‹the query function uses.



0


source


You cannot transfer stuff from one instance to another without initializing a new class with information about other instances. So you can extend A to change the content of B's โ€‹โ€‹request function, and then initialize B with an instance of A:

class A {
    protected $propa = "";
    protected $propb = "";
    //etc

function query { /*...*/ }
}

class B extends A {
    function __construct( A $classA )
    {
        $this->propa = $classA->propa;
        // etc
    }
    function query()
    {
        //B-type queries
    }
}

$A = new A();
// set stuff in a
new B( $A );

      

If A and B are 100% the same (including the query function), then just clone A: $ a = new A (); $ b = clone $ a;

0


source


what would you like to use properties in class A and class B? you can do this using the parent. in class B:

function queries(){
  $queries = array()
   //stuff to get queries

  return array_merge($queries,parent::queries());
}

      

0


source







All Articles