Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create own PHP class in wordpress theme function?

Tags:

php

wordpress

I have created a bunch of functions for my wordpress theme. I am thinking to put all function inside a class. So that I can call it using:

<?php $foo->function() ;?>

I want to know if I put my functions inside php class then will it cause any problem??? Please note I am using WordPress function inside my functions.

UPDATE

class foo{
    function js($files){
        $css    =   array($files);
        foreach($css as $style){
            wp_enqueue_script($style, get_template_directory_uri() . '/js/'.$style, array(), '', true );
        }

    }
}
$foo = new foo();

It works well when I call it directly:

$foo->js('bootstrap-transition.js,bootstrap-modal.js,bootstrap-dropdown.js');

but when i call it insde another function like this:

function assets(){
    $foo->js('bootstrap-transition.js,bootstrap-modal.js,bootstrap-dropdown.js');
}

then it shows Call to a member function on a non-object error

like image 458
user007 Avatar asked Dec 01 '22 21:12

user007


2 Answers

This is how I usually do it, for example, in functions.php (very simplified):

Myclass::init();

class MyClass
{
  // Add filters and actions here
  function init()
  {
    add_filter('pre_get_posts', array(__CLASS__, 'query_posts'));
  }

  function query_posts($query)
  {
    global $post; // you can use WP variables and functions
    // do something with $query
  }

  function navigation()
  {
    ?>
    <ul>
      <li><a href="<?= home_url() ?>">Home</a></li>
    </ul>
    <?php
  }
}

Using this pattern you can organize all your functions inside a static class (doesn't need to be instantiated) and then you can call functions in any template like so:

<?php MyClass::navigation() ?>

Hope this helps.

like image 40
elclanrs Avatar answered Dec 04 '22 02:12

elclanrs


Here is a basic primer about Object Oriented Programming in PHP for those that are not yet familiar with the concepts. Objects are containers. They contain the definition functions and variables that represent a single abstract entity. This feature of Object Oriented Programming is called encapsulation. It means that a single capsule may contain the definition of multiple functions and variables that are meant to work together.

For instance, if you want to manipulate a product being sold in a e-commerce site, you can have an object that represents that product. It probably contains some variables that define the product name, description,price, etc.. It may also contain some functions to manipulate the object variables, store or retrieve the values of the product from a database, display the product details, etc..

In PHP objects are defined using classes. A class contains all the definitions of functions and variables that describe an object.

Here is a sample of simple product class:

 class Product
 {
   var $name;
   var $description;
   var $price;



function RetrieveFromDatabase($id)
   {
     /* ... */
   }

   function Display()
   {
     echo 'Name: ', HtmlSpecialChars($this->name),
       '<br>',
       'Description: ', HtmlSpecialChars($this->description),
       '<br>',
       'Price: ', $this->price; 
   }
 };

You can create an object using the new operator. A PHP script can create multiple objects of the same class. You can have two distince products for sale in your e-commerce site defined by the same class.

For instance, if you have for sale the book A and the book B, you can use the same class to manipulate its name, description, price, etc.. Here follows an example of how to create PHP objects:

$book_a = new Product();
 $book_a->name = 'Book A';
 $book_a->description = 'Some description of book A';
 $book_a->price = 9.95;
 $book_a->Display();

 $book_b = new Product();
 $book_b->RetrieveFromDatabase('id-of-book-b');
 $book_b->Display();

Classes allow you to manipulate information internally without having to use global variables to share information between different class functions.

For instance if you want to retrieve and display database query results, you can have a class with a function to execute the query and another function to display it. They use the class variables $results to store and retrieve the query results handle.

 class Query
 {
   var $results;

   function Execute($query)
   {
     $this->results = mysql_query($query);
     return $this->results !== false;
   }

   function Display()
   {
     while(($row = mysql_fetch_row($this->results)))
       print_r($row);
   }
 };

 $query = new Query;
 if($query->Execute(
   'SELECT name, description, price FROM product'
 ))
   $query->Display();

As you may see, you do not need to use any global functions nor any global variables to share information between the class functions. All the behavior of the products is encapsulated inside the Query class.

Object Oriented Programming provides other important features such as inheritance, which allows creating new classes that are extensions of existing classes. The extension classes may have more functions and variables. They may also redefine functions and variables already defined in the base class.

Resource Link for Object Oriented Programming with Classes

like image 119
Jhonathan H. Avatar answered Dec 04 '22 04:12

Jhonathan H.