2017-09-05 53 views
1

我需要getdata()函数class-GetData.php在此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(); 
} 
?> 

类访问getdata.php

<?php 

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

    $getData = new GetData(); 

但我正在逐渐未定义功能错误:

Call to undefined function getdata()

+1

'的getData()'是在'GetData'类*方法*。你需要使用'$ getData-> getData()',调用对象的方法。通常,您不会通过 – Qirel

+0

'$ getData-> getdata()' – Und3rTow

+1

来初始化类文件中的对象。请参阅http://php.net/manual/en/language.types.object.php和http:/ /php.net/manual/en/language.oop5.basic.php – Qirel

回答

1

使用的GetData类的对象调用的类创建的功能。

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(); 
} 

类访问getdata.php

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

你也许想解释一下你的答案?原始代码已经发生了什么变化,您为什么改变它?总是有一些文字来解释你的答案。 – Qirel

2

要调用Class Method像正常的函数调用。内部Class Method需要this关键字来调用一个类中的方法。如果您想从班级以外拨打Public功能/方法,您必须创建一个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

+0

或者你可以像'(new GetData()) - > getdata()' –

+0

一样使用吗?你是否想要解释一下你的答案?原始代码已经发生了什么变化,您为什么改变它?总是有一些文字来解释你的答案。为什么要有人“*尝试使用*”这个? – Qirel

+0

啊是的!我正在更新我的答案。谢谢@Qirel –