I have very basic knowledge of OOP in PHP and am trying to learn to use namespaces in WordPress plugins. Followed some instructions from these 2 sources:

  1. WPSE 63668
  2. Paulund

This is how my current code looks:

Root Folder: plugins/oowp

File: oowp/bootstrap.php

<?php
/*
Plugin name: OOWP
*/
require_once('autoload.php');

File: oowp/autoload.php

<?php
spl_autoload_register('autoload_function');
function autoload_function( $classname )
{
    $class = str_replace( '\\', DIRECTORY_SEPARATOR, str_replace( '_', '-', strtolower($classname) ) );

    // create the actual filepath
    $filePath = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . '.php';

    // check if the file exists
    if(file_exists($filePath))
    {
        // require once on the file
        require_once $filePath;
    }
}

File: oowp/objects/custom-objects.php

<?php

namespace oowp\objects;

class Custom_Objects {
    public function __construct() {
        add_action('plugins_loaded', array($this, 'trial'));
    }

    public function trial() {
        echo 'Works';
    }
}

How and where do I initiate this class? Do I need to write another class which starts the processing? I tried creating the instance of the custom-objects class in the file itself but it doesn’t work.

1
1

Give it a try like so:

File: oowp/bootstrap.php

<?php
/*
Plugin name: OOWP
*/

require_once( 'autoload.php' );

use oowp\objects\Custom_Objects;

new Custom_Objects;

Leave a Reply

Your email address will not be published. Required fields are marked *