How to make constant member functions in Php?

Asked

Viewed 38 times

-1

I was studying what my book called "constant member functions" in C++. i.e., functions that cannot change any class attribute or call other methods that are not constant. So, I made this code in C++.

#include <iostream>
#include <string>

using namespace std;


class Foo
{
     string outra_coisa;
  public: 
    void printa_algo(string algo) const;
};

int main()
{
    Foo tolo;
    string alguma_coisa = "coisa_alguma";
    tolo.printa_algo(alguma_coisa);

    return 0;
}

void Foo::printa_algo(string algo) const
{
    cout << algo;
}

It is possible to do the same in PHP?

  • What the title has to do with that code?

  • Bruno gives yes for sure, but, really the title does not match the question!

  • Vish is msm...pera ae.. Tidy.

2 answers

0

I think you’re referring to static functions, which can be called without creating an instance of the class, and which cannot modify properties and members of the class, if so, just use the keyword static:

<?php
class Foo {
    public static function Bar() {
        echo 'Olá, mundo!';
    }
}

// você pode chamar assim
Foo::Bar();

// ou assim
$classname = 'Foo';
$classname::Bar();

// mas não assim
$class = new Foo;
$class->Bar(); // erro
?>
  • I am aware about static functions, the question was even about constant methods.

  • Correct me if I’m wrong, but I don’t think this exists in PHP.

-1


Well after some research I saw in a book that is not possible, at least it is not trivial, create such functions in Php. You can create methods that don’t make changes in attributes, but cannot create methods who can’t do amendments in no way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.