Why is access and visibility mixed up in PHP?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



(I've posted this to the PHP newsgroups, as well, but as many here might not
read them, I post here, as well. I hope that's not considered "overboard",
and if so, please let me know)

Well, as is customary when you're new to a group, you tend to post quite a
bit, :) so here's one more. Some things I've been wondering about with PHP
(5).

Today, I worked on an implementation of a finite state machine. Unlike the
pear::fsm, this one supports hierarchical states, and I intend to make it
available, as well. It exists in both PHP 4 and 5 versions, but only the
PHP5 version is relevant for this example. The base class defines some
(virtual) functions that may be overridden in a derived class, but they are
only called from the base class. My original code was as follows (I only
quote the bare minimum needed for illustration):

class fsm
{
  ...
  public function process($signal)
  {
    // null_action() is called from here (unless another action function is
specified for a transition)
  }

  private function null_action($from_state,$to_state)
  {
  }
}

class my_fsm extends fsm
{
  private function null_action($from_state,$to_state)
  {
    echo "Transition from $from_state to $to_state";
  }
}

In C++ this would work just fine: As null_action() is called from fsm, and
it's private in fsm, this works fine. It gets overridden in my_fsm, but
being private in fsm, it can only be called there (not in my_fsm), which is
as intended. This is because access and visibility are orthogonal concepts
in C++: The access specifiers only specify who are allowed to access (as in
calling, taking the address of, etc.) a function, but it doesn't affect
overriding.

The reason for this is as follows (from "The Design and Evolution of C++"):
By not letting the access specifiers affect visibility (including
overriding), changing the access specifiers of functions won't affect the
program semantics.

However, this is not so for PHP...

The above won't work, or at least not work as intended: The function
null_action() will only be visible in the class it's defined, and therefore
the derived class version won't override the base class version. In order to
get it to work, the access specifiers have to be changed to protected. This
means that derived classes may also _call_ the function, something that is
not desired. This means I can't enforce this design constraint of having
this function private.

Why is it done like this?

Regards,

Terje

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux