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
Kinderly WadeprogrammerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Kinderly WadeprogrammerAuthor 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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 WadeprogrammerAuthor 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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.