PHP function inside another function [ class ]

I have the following code, perform a global function within a class to fill the functions of wordpress, the problem is that the only way that I could get a variable public class is as follows

class Core {
 public $notice;
 function __construct(){
  $this->core_function();

 }
 function core_function(){
   global $globalvar;
   $globalvar = $this;
   function notice_global(){
    global $globalvar;

    return $globalvar->notice;

   } 
 }
 function set_notice(){
  $this->notice = array('Warning');
 }

}

$GP = new Core();
$GP->set_notice();
var_dump(notice_global());

Any other ideas or suggestions, this code is correct or not?

Related posts

3 comments

  1. As you said in the comments, you need global function due to wordpress hook method (for a plugin, I suppose).

    This is not necessary: there is a way to pass an object method (not a whole object) to wordpress.

    You can try in this way:

    class Core {
        public $notice;
    
        function get_notice()
        { return $this->notice; }
    
        function set_notice()
        { $this->notice = array('Warning'); }
    }
    
    $GP = new Core();
    $GP->set_notice();
    
    add_action( 'save_post', array( $GP, 'get_notice' ) );
    

    Or – for a better flexibility – in this way:

    class Core {
        public $notice;
    
        function get_notice()
        { return $this->notice; }
    
        function set_notice()
        { $this->notice = array('Warning'); }
    
        function add_wp_action( $hook, $method )
        { add_action( $hook, array( $this, $method ) ); }
    }
    
    $GP = new Core();
    $GP->set_notice();
    
    $GP->add_wp_action( 'save_post', 'get_notice' );
    

    By this way, you can directly set all your wp hooks in the class and call they directly with an object method, without using globals variables or function tricks.

  2. I’m not sure if I’m understanding you right, but notice_global can be moved out of that class.

    Globals have scope outside of classes

  3. There is no need for these functions. You’ve defined $notice as public property. You can access it like this: $GP->notice;

    You might also want to read documentation on visibility of methods and properties.

Comments are closed.