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 concept below works, but something smells wrong:
<?php // plugin.php namespace Q\Plugin; // If this file is called directly, Bulk! if ( ! defined( 'ABSPATH' ) ) { return; } // autoloader ## require_once __DIR__ . '/autoload.php'; // 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 \Q\Plugin\CPT([ '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 Q\Plugin\CPT; class CPT extends \Q\Plugin { // 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!