1

I need the getdata() function from class-GetData.php to call inside this shortcode_function().

require_once plugin_dir_path( __FILE__ ) . '/class-GetData.php';

add_shortcode('registration-plugin','shortcode_function');    
function shortcode_function()
{
    ob_start();
    insert_data();
    getdata();   //from GetData.php
    return ob_get_clean();
}
?>

class-GetData.php

<?php

    class GetData
    {
       public function getdata()
       { 
          //something here
       }
    }

    $getData = new GetData();

But i am getting undefined function error:

Call to undefined function getdata()

Steve
  • 1,622
  • 5
  • 21
  • 39
  • 1
    `getData()` is a *method* in the `GetData` class. You need to use `$getData->getData()`, call the method on the object. Usually, you wouldn't initialize the object in the class-file though – Qirel Sep 05 '17 at 09:17
  • `$getData->getdata()` – Michael Doye Sep 05 '17 at 09:18
  • 1
    See http://php.net/manual/en/language.types.object.php and http://php.net/manual/en/language.oop5.basic.php – Qirel Sep 05 '17 at 09:18

2 Answers2

1

Use the object of GetData class to call the function created in the class.

require_once plugin_dir_path( __FILE__ ) . '/class-GetData.php';

add_shortcode('registration-plugin','shortcode_function');    
function shortcode_function()
{
    ob_start();
    insert_data();
    $getData = new GetData(); //Create Getdata object
    $getData->getdata(); //call function using the object
    return ob_get_clean();
}

class-GetData.php

class GetData
{
   public function getdata()
   { 
      //something here
   }
}
noufalcep
  • 3,446
  • 15
  • 33
  • 51
  • 1
    Do you perhaps want to explain your answer a bit? What has been changed from the original code, and why did you change that? Always have some text to explain your answer. – Qirel Sep 05 '17 at 09:24
1

You are calling Class Method like as normal function calling. Inner Class Method need this keyword to call a method in a Class. If you want to call Public function/method from outside of the class, You have to create an Object.

Try to use -

function shortcode_function(){
  ob_start();
  insert_data();
  $getData = new GetData(); #Create an Object
  $getData->getdata();      #Call method using Object
  return ob_get_clean();
}

Example :

class GetData{
   public function getdata() { 
      //something here
   }

   public function TestMethod(){
      $this->getdata(); #Calling Function From Inner Class
   }
}

$getData = new GetData(); #Creating Object
$getData->getdata();      #Calling Public Function from Outer Class

Here is the explanation for Private,Public and Protected

Sumon Sarker
  • 2,707
  • 1
  • 23
  • 36