Brandon Benefield
Brandon Benefield

Reputation: 1672

Property Scope in PHP Classes

What I Need

Ability to access prop $result, defined inside of method fill_default_values, inside of method html.

Summary

I have two methods, fill_default_values and html inside of a class Admin. I'm having trouble getting access to a prop, $result, from inside of fill_default_values when calling it inside of html.

Code

fill_default_values

  // grabs values from DB and fills inputs on ADMIN PAGE
  protected static function fill_default_values() {
    global $wpdb;

    $table_name = $wpdb->prefix.'bb_slidersettings';
    $result = $wpdb->get_results(
      "SELECT
       id
       FROM
       $table_name;"
    );

    if (!$result) {
    ?>

      <small class="text-red">Something went wrong</small>

    <?php
    } // endif

    return $result;
  }// fill_default_values()

html

  // Outputs HTML to main admin page
  public static function html() {
    self::fill_default_values();

    ?>

    <!-- BEGIN HTML -->
    <form id="bb-carousel-form" action="" method="POST">
      <input name="carousel_id" type="hidden" value="<?php echo $result[0]->id; ?>">
  }

You can see that I create the fill_default_values method and call it from inside of html where I would expect $result to be available. Instead I get this error message.

error

<br />
<b>Notice</b>:  Undefined variable: result in <b>[FILE PATH]</b> on line <b>120</b><br />
<br />
<b>Notice</b>:  Trying to get property 'id' of non-object in <b>[FILE PATH]</b> on line <b>120</b><br />

Oddly enough, if I were to move the entirety of fill_default_values into html everything works like a charm.

Upvotes: 0

Views: 51

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94682

You need to capture the returned value like this

$result = self::fill_default_values();

Then $result should have a value

Upvotes: 1

Related Questions