OOP: Instantiate plugin, passing parameters and accessing super class properties from sub class object
Question
I would like to know the "best" – OOP-way – and WP-compatible – format for instantiating an object, while passing arguments ( which are defined as properties in the parent class ) – which are then cleanly and correctly available to all sub classes, which extend the parent.
I would like to know how to make $this->slug ( the parent prop ) available cleanly within the sub class, without having to pass the arguments to this class constructor.
The example code below works, but something smells wrong:
<?php
// plugin.php
namespace QPlugin;
// Define Class ##
class Plugin {
// class properties ##
protected $slug = false;
// construct ##
public function __construct( Array $args = [] ) {
// set class props, if defined - check using null coalescing operator ##
$this->slug = $args['slug'] ?? false ;
}
// public init callback ##
public function init() {
// setup CPT ##
$cpt = new QPluginCPT([
'slug' => $this->slug,
]);
$cpt->init();
}
}
// instantiate the plugin class and make the returned object available as a (optional) global variable ##
global $q_plugin;
$q_plugin = new Plugin([
'slug' => 'q_cpt', // cpt slug -- singular ##
]);
$q_plugin->init();
// NAMESPACE/cpt.php
namespace QPluginCPT;
class CPT {
// construct ##
public function __construct( Array $args = [] ) {
// store passed args ##
$this->args = $args;
}
// public init callback ##
public function init() {
// sanity ##
if(
! isset( $this->args['slug'] )
){
error_log( 'Error in params passed to '.__CLASS__ );
return false;
}
// $this->args['slug'] is now available to use in register_post_type function
// BUT, I would like to know how to make $this->slug ( the parent prop ) available cleanly, without having to pass the arguments to this class constructor
}
}
Thanks!
0
2 months
0 Answers
35 views
0
Leave an answer
You must login or register to add a new answer .