[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2060
  • Last Modified:

calling a private non-static function inside a public static function

Dear experts

I wish to know if it is possible to call a private function from a class into a public static function in same class?
If possible how can I access the private function? Thanks
0
Kinderly Wade
Asked:
Kinderly Wade
  • 4
  • 2
  • 2
  • +1
1 Solution
 
gheistCommented:
Yes, nothing prevents you from calling public function.
0
 
Ray PaseurCommented:
...call a private function from a class into a public static function...
Why?

I think the concept you want to learn about is "visibility."
http://www.php.net/manual/en/language.oop5.visibility.php

But that aside, this sounds the sort of question that has a subtext or a back-story.  Please let us know how experienced you are with PHP and object-oriented programming.  Can you tell us a little about the application?
0
 
Steve BinkCommented:
Aside from visibility concerns, there's also a question of application.

If you are calling a public static function, that means there is no $this object.  Static functions act in the context of the class definition, not a specific instance.

Meanwhile, a non-static function's context is within a specific instance of a class.  It is not just a definition at that point, but an implementation.  Having a private/protected function in the class definition means that only the owning instance (or its descendants, in the case of protected) know anything about the function.  So, while your static function is a member of the class, and can even be called from the instance, what instance will it use to call the non-static method?  

In reality, PHP is a bit more forgiving - the call you describe CAN be done, but PHP's strict error reporting will complain about it.  One solution is to pass the instance as a parameter.
<?php
class A {
  private function myPrivate() {
    print_r("in private\n");
  }
  public static function myPublicStatic() {
    print_r("in static\n");
    self::myPrivate();
  }
  public static function myPublicWithParameter($instance) {
    print_r("in static parameterized\n");
    $instance->myPrivate();
  }
}

A::myPublicStatic();
print_r("---------------\n");
$a = new A();
$a::myPublicStatic();
print_r("---------------\n");
A::myPublicWithParameter($a);
print_r("---------------\n");

/*  output:

in static

Strict Standards: Non-static method A::myPrivate() should not be called statically in C:\websrv\static-test.php on line 8
in private
---------------
in static

Strict Standards: Non-static method A::myPrivate() should not be called statically in C:\websrv\static-test.php on line 8
in private
---------------
in static parameterized
in private
---------------

*/

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Kinderly WadeAuthor Commented:
Hi all,

I have a singleton instance that can be called but I wish to include an private function within this public static function like this:

class test
{
private msgTest()
{
      echo 'hello world';
}


public function __construct()
{
    echo 'my new instance';
}

public static function callInstance()
{
    self::$instance = new self();
    self::msgTest();
}

}

Open in new window


but this doesn't seem to work. I've tried $this->msgTest() with public non-static function and it works with those.
I tried self but somehow I got errors.

This makes me wondering if I can call a private function into a public static function. Thanks.

Sorry maybe my previous question wasn't clear =).
0
 
Ray PaseurCommented:
That code contains a parse error.  Please explain what you want to achieve by this design -- perhaps we can suggest something that will work for your needs.

If you're after a singleton example, this may do (add your own credentials and you should be able to use it to connect to a database).  But please read the common literature about the issues with the singleton design pattern.

<?php // demo/oop_database_singleton.php
error_reporting(E_ALL);


// SINGLETON DATA BASE CONNECTION CLASS
class Database
{
    // CLASS PROPERTIES ARE ALL PRIVATE
    private static $connection;
    private static $instance;

    // CONNECTION VALUES
    const DB_HOST = '?';
    const DB_USER = '?';
    const DB_PASS = '?';
    const DB_NAME = '?';

    // NULLIFY THE CLONE AND THE WAKEUP
    final private function __clone() {}
    final private function __wakeup() {}

    // OUR ONLY PUBLIC METHOD RETURNS THE CONNECTION
    final public static function getConnection()
    {
        if (!self::$instance) self::$instance = new self();
        return self::$connection;
    }

    // CONSTRUCTOR CREATES THE CONNECTION
    final private function __construct()
    {
        self::$connection
        = new mysqli
        ( self::DB_HOST
        , self::DB_USER
        , self::DB_PASS
        , self::DB_NAME
        )
        ;
        if (self::$connection->connect_error)
        {
            trigger_error(self::$connection->connect_error, E_USER_ERROR);
        }
    }
}


// SHOW WHAT HAPPENS WHEN YOU TRY TO MAKE TWO CONNECTIONS
$dbc_1 = database::getConnection();
$dbc_2 = database::getConnection();


// PROVE THAT THESE ARE THE SAME OBJECT http://php.net/manual/en/language.oop5.object-comparison.php
if ($dbc_1 === $dbc_2) echo 'EQUAL! ';

// SHOW THE OBJECT
var_dump($dbc_2);

Open in new window

0
 
Steve BinkCommented:
A simpler example of what you're trying to do.  Note that __construct() function is private - a singleton should be controlling the creation process.  Also, the getInstance() method checks for population before creation.
<?php
class A {
  private static $instance;

  private function __construct() {
    $this->my_value = 'foo';
    echo "creating the instance\n";
  }

  private function myFunction() {
    echo "function says {$this->my_value}\n";
  }

  public static function getInstance() {
    if (!self::$instance) {
      self::$instance = new self();
    }
    echo "have an instance \n";
    self::$instance->myFunction();
  }
}

$a = A::getInstance();
$b = A::getInstance();

/* output:

creating the instance      <-- note that only one instance was created
have an instance
function says foo
have an instance              <-- this found the existing instance
function says foo 
*/

Open in new window

0
 
Ray PaseurCommented:
Before you start using a singleton for anything, you might want to understand why you should not use singletons.  In a nutshell, the Singleton Design Pattern creates conditions you do not want, including code that cannot be mocked, and is therefore unusable with automated testing.
http://www.object-oriented-security.org/lets-argue/singletons
0
 
Kinderly WadeAuthor Commented:
Hi Ray,

Thanks for great information upon the object oriented design. I am still new to the objects and just trying to explore out some possibilities that I can do and cannot do with it.
 
I bet I will have some question down the line of OOD and I will definitely seek for some of your great suggestions.

The security reference links that you send to me the other day was really useful. I am using it as a reference when coding my web page.

Thanks again.
0
 
Ray PaseurCommented:
Look up Brandon Savage (Google him) and consider getting some of his materials on OOD and OOP.  He's a professional friend and (in addition to being able to fly) very conversant on the PHP side of object-oriented things.  Also, our E-E colleague @gr8gonzo has a couple of well-written articles here about OOP.

http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/A_2626-Beginning-Object-Oriented-Programming-in-PHP.html

http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/A_2631-Advanced-Object-Oriented-Programming-in-PHP.html
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now