Jump to content

Sub/Child Class Override


haymanpl

Recommended Posts

I need to add more code to an existing function located inside the parent class. I'm using code like this but can't get it working :


 

// Parent

class Default_Fields {

    public function fields() {

        $this->_fields = array()
            
        // Default Code
    }

}


// Child

class More_Fields extends Default_Fields {

    public function fields() {

        $this->_fields = array()
            
        // Modified Code
    }

}


$new = new More_Fields;

$new->fields();


The modified code in the child class is an extended version of whats in the parent. There's no errors but the additional code is not printing.

Edited by haymanpl
Link to comment
Share on other sites

It doesn't make sense to override a method with the same exact method.

How about telling us what the real problem is you are trying to solve instead of asking about your attempted solution to solving it.

 

Quote

the additional code is not printing.

How do you expect it to print anything when there is no code to output anything? No echo, no return, no nothing.

Edited by benanamen
Link to comment
Share on other sites

1 hour ago, benanamen said:
Quote

the additional code is not printing.

How do you expect it to print anything when there is no code to output anything? No echo, no return, no nothing.

Also, there is no additional code. It's the same code twice. I'll add to benanamen's request and ask that you post the actual code along with the actual problem.

Link to comment
Share on other sites

Here's the actual code which adds another text field.

// Parent

class Default_Fields {

    public function fields() {

        $this->_fields = array()
            
       array(
                'name'        => 'text_one',
                'label'       => __( 'Text One' ),
                'type'        => 'text',
            ),
            
        );    
    }

}


// Child 

class More_Fields extends Default_Fields {

    public function fields() {

        $this->_fields = array()
            
        array(
                'name'        => 'text_one',
                'label'       => __( 'Text One' ),
                'type'        => 'text',
            ),
        array(
                'name'        => 'text_two',
                'label'       => __( 'Text Two' ),
                'type'        => 'text',
            ),
        );    
    }

}


$new = new More_Fields;

$new->fields();

 

Link to comment
Share on other sites

4 hours ago, Barand said:

You really need to turn on the error reporting. That code won't even run, let alone produce incorrect results.

Error reporting is turned on. Runs because i tested it but it doesn't add the extra field.

 

Can anyone else help?

Edited by haymanpl
Link to comment
Share on other sites

18 hours ago, maxxd said:

Also, there is no additional code. It's the same code twice. I'll add to benanamen's request and ask that you post the actual code along with the actual problem.

Alex, i'm simply trying to add another field to the parent class using a child class. The parent class already executes the code.

Link to comment
Share on other sites

1 hour ago, haymanpl said:

Runs because i tested it

Then how about posting the code that "works" because that code above contains syntax errors and undefined function calls.

 

22 hours ago, haymanpl said:

There's no errors but the additional code is not printing.

There is no code there to print anything (except throw error messages of course)

Link to comment
Share on other sites

BEWARE

This user @haymanpl will threaten you with physical violence if he doesn't like your post. The exact response on the cross post that prompted this user was "Didnt you like the help you were getting on the other forum" (This one).

 

Quote

Dickhead Kevin. Stop behaving like another useless troll from the most hated country on the planet. No wonder America has 450 mass shootings every year and the highest incaceration rate in the world. Within the next 5 - 7 years your country will have over 1000 mass shootings. It’s because of weak cowards like you there’s so much hatred in your shitty little country which fuels the mass murder of hundreds of thousands of Mexicans your country uses to supply drugs to Americans. 20% of your entire country is on drugs. You would never behave like that to me face to face because i would bash your brains in. Something, you can avoid for the time being while you will need to hide for the rest of your life. I won’t forget you Kevin!

 

Edited by benanamen
Link to comment
Share on other sites

I've cleaned it up, provided the missing function definition and added something that prints,  but it's only a guess at what you really want.

function __($text)
{
    return $text;               // or whatever else it is suppoesed to do

} 

                               
// Parent

class Default_Fields {
    
    protected $_fields = [];

    public function fields() 
    {

        $this->_fields = array(
                           array(
                                    'name'        => 'text_one',
                                    'label'       => __('Text One'),
                                    'type'        => 'text',
                                )
                        );    
    }

    public function showFields()
    {
        echo 'Output from class: ' . get_class($this);
        echo '<pre>', print_r($this->_fields, 1), '</pre><hr>';
    }
}


// Child 

class More_Fields extends Default_Fields {

    public function fields() {

        parent::fields();                                                       // call default
        $this->_fields[] = array(                                               // add extra field
                                    'name'        => 'text_two',
                                    'label'       => __('Text Two'),
                                    'type'        => 'text',
                            );    
    }

}

$old = new Default_Fields();
$old->fields();
$old->showFields();

$new = new More_Fields;
$new->fields();
$new->showFields();

 

Link to comment
Share on other sites

On 9/30/2019 at 4:25 PM, Barand said:

I've cleaned it up, provided the missing function definition and added something that prints,  but it's only a guess at what you really want.


function __($text)
{
    return $text;               // or whatever else it is suppoesed to do

} 

                               
// Parent

class Default_Fields {
    
    protected $_fields = [];

    public function fields() 
    {

        $this->_fields = array(
                           array(
                                    'name'        => 'text_one',
                                    'label'       => __('Text One'),
                                    'type'        => 'text',
                                )
                        );    
    }

    public function showFields()
    {
        echo 'Output from class: ' . get_class($this);
        echo '<pre>', print_r($this->_fields, 1), '</pre><hr>';
    }
}


// Child 

class More_Fields extends Default_Fields {

    public function fields() {

        parent::fields();                                                       // call default
        $this->_fields[] = array(                                               // add extra field
                                    'name'        => 'text_two',
                                    'label'       => __('Text Two'),
                                    'type'        => 'text',
                            );    
    }

}

$old = new Default_Fields();
$old->fields();
$old->showFields();

$new = new More_Fields;
$new->fields();
$new->showFields();

 

Thanks Barand. The only problem is the original function for the output showFields(), is not located inside the original parent class file. It's added in the functions file.
 

  function admin_fields( $post_id = '' ) {

    // Output Code

    }

 

Link to comment
Share on other sites

28 minutes ago, Barand said:

Then "protected $_fields" will need to be "public $_fields" if you want to access them from outside the classes.

The fields in the parent class are private

private $_fields;

However, the access to the fields() function is public

  @access public

I can simply create a new function for the output and add the extra fields however for some reason this doesn't change the input fields() function in admin.

There are no errors.

Is there another way to do this?

Edited by haymanpl
Link to comment
Share on other sites

If they are private in the parent class they are only accessible to the parent class and not available even to subclasses, which is why I used  "protected", to make available to subclasses also.

With "private" the subclass has two $_fields, the one it inherited and its own private one.

46 minutes ago, haymanpl said:

Is there another way to do this?

Use "protected" and provide a getter function to get the $_fields from within the class ...

<?php

/*****************************************************************************
* 
*                EXTERNAL FUNCTIONS
* 
******************************************************************************/
function __($text)
{
    return $text;               // or whatever else it is suppoesed to do

} 

function showFields($obj)
{
    $flds = $obj->getFields();
    echo '<h4>Class : ' . get_class($obj) . '</h4>';
    echo "<table border='1' style='border-collapse:collapse'>\n<tr><th>Name</th><th>Label</th><th>Type</th></tr>\n";
    foreach ($flds as $f) {
        echo "<tr><td>{$f['name']}</td><td>{$f['label']}</td><td>{$f['type']}</td></tr>\n";
    }
    echo "</table><br>\n";
}


/*****************************************************************************
* 
*                CLASSES
* 
******************************************************************************/
                              
// Parent

class Default_Fields {
    
    protected $_fields = [];

    public function fields() 
    {

        $this->_fields = array(
                           array(
                                    'name'        => 'text_one',
                                    'label'       => __('Text One'),
                                    'type'        => 'text',
                                )
                        );    
    }
    
    public function getFields()
    {
        return $this->_fields;
    }
}
     

// Child 

class More_Fields extends Default_Fields {

    public function fields() {

        parent::fields();                                                       // call default
        $this->_fields[] = array(                                               // add extra field
                                    'name'        => 'text_two',
                                    'label'       => __('Text Two'),
                                    'type'        => 'text',
                            );    
    }

}

$old = new Default_Fields();
$old->fields();
showFields($old);

$new = new More_Fields;
$new->fields();
showFields($new);
?>

 

Link to comment
Share on other sites

1 hour ago, Barand said:

If they are private in the parent class they are only accessible to the parent class and not available even to subclasses, which is why I used  "protected", to make available to subclasses also.

With "private" the subclass has two $_fields, the one it inherited and its own private one.

Use "protected" and provide a getter function to get the $_fields from within the class ...


<?php

/*****************************************************************************
* 
*                EXTERNAL FUNCTIONS
* 
******************************************************************************/
function __($text)
{
    return $text;               // or whatever else it is suppoesed to do

} 

function showFields($obj)
{
    $flds = $obj->getFields();
    echo '<h4>Class : ' . get_class($obj) . '</h4>';
    echo "<table border='1' style='border-collapse:collapse'>\n<tr><th>Name</th><th>Label</th><th>Type</th></tr>\n";
    foreach ($flds as $f) {
        echo "<tr><td>{$f['name']}</td><td>{$f['label']}</td><td>{$f['type']}</td></tr>\n";
    }
    echo "</table><br>\n";
}


/*****************************************************************************
* 
*                CLASSES
* 
******************************************************************************/
                              
// Parent

class Default_Fields {
    
    protected $_fields = [];

    public function fields() 
    {

        $this->_fields = array(
                           array(
                                    'name'        => 'text_one',
                                    'label'       => __('Text One'),
                                    'type'        => 'text',
                                )
                        );    
    }
    
    public function getFields()
    {
        return $this->_fields;
    }
}
     

// Child 

class More_Fields extends Default_Fields {

    public function fields() {

        parent::fields();                                                       // call default
        $this->_fields[] = array(                                               // add extra field
                                    'name'        => 'text_two',
                                    'label'       => __('Text Two'),
                                    'type'        => 'text',
                            );    
    }

}

$old = new Default_Fields();
$old->fields();
showFields($old);

$new = new More_Fields;
$new->fields();
showFields($new);
?>

 

Can't use protected as the $fields are already private in the parent class. I'm trying to modify the parent class using a child class.

Link to comment
Share on other sites

29 minutes ago, Barand said:

What changes can you make to the parent?

Does the parent have a getFields() method (or similar)?

How is your external "showFields()" function getting the fields to show?

If not, are you able to add one?

Does the parent class have a method for adding fields?

All functions within the parent class are public.

There's no getFields().

It uses custom fields.

Thats why i uses a child class to extend the default parent theme function and add more fields.

There's 2 functions for the fields. 1 for the input which is this :

function fields() {

        $this->_fields = array(
                           array(
                                    'name'        => 'text_one',
                                    'label'       => __('Text One'),
                                    'type'        => 'text',
                                )
                        );    
    }

And 1 for the output which is NOT contained within the parent class.

function get_more_fields() {

	$text_fields = array( 'text_one', 'text_two', 'text_three', 'text_four', 'text_five' );
	$values  = array();

    // Code

	return $values;

}

 

Link to comment
Share on other sites

19 minutes ago, Barand said:

How is your current external showFields() function getting that data from the default class?

It uses several functions within the parent class and then loads the fields in admin using get_meta_box.

When i test the child class using this code, it outputs correctly so the child class is loading correctly, its just not appending the new fields to the existing fields coded in the parent class.

  function test() {

    add_action('admin_notices', function(){
        print '<div class="updated">' . __CLASS__ . ' loaded!</div>';
    });

    }

$new = new More_Fields();
$new->test();

 

Link to comment
Share on other sites

59 minutes ago, Barand said:

What is the relation ship between $Text_Meta and your Default_Fields class?

$text_meta  is equal to the custom field value as seen in this external function


// Gets the text meta data value from the provided key.

function get_text_meta( $key, $post_id = '' ){

	$post_id =  $post_id ? $post_id : get_the_ID();

	$text_meta = get_post_meta( $post_id, '_text_field_meta', true );

	if( empty( $text_meta[$key] ) ){
		return false;
	}

	return $text_meta[$key];

}

Note : When i add the extra text fields in the parent theme class for testing, it works, meaning i only need to modify the default fields() function.

Edited by haymanpl
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.