5

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.

5

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;
  • You're great! It works! So if I want to call functions from multiple classes, I should initiate them in bootstrap.php? Any tips to improve my setup and make it better? – Rutwick Gangurde Jul 9 '15 at 14:48
  • I don't understand what do you mean by So if I want to call functions from multiple classes, I should initiate them in bootstrap.php? You have to make sure you have a reference to what class you wish to have access to by using the 'use' operator. For a lot of more information you can browse the online manual. – webtoure Jul 9 '15 at 15:04
  • Thanks again. I will use only the class which serves as an entry to my code's execution. – Rutwick Gangurde Jul 10 '15 at 5:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.