Main function in php class

Calling a function within a Class method?

I have been trying to figure out how to go about doing this but I am not quite sure how. Here is an example of what I am trying to do:

class test < public newTest()< function bigTest()< //Big Test Here >function smallTest() < //Small Test Here >> public scoreTest() < //Scoring code here; >> 

Just to make sure: a function and a method is exactly the same function === method. The term method is more often used in OO language to describe the function of a class.

The reason some of the terms are missing is I was on my way out of the office, so I was short on time.

10 Answers 10

class test < public function newTest()< $this->bigTest(); $this->smallTest(); > private function bigTest() < //Big Test Here >private function smallTest() < //Small Test Here >public function scoreTest() < //Scoring code here; >> $testObject = new test(); $testObject->newTest(); $testObject->scoreTest(); 

Is it possible to run a function() from another .php page inside a class function and then grab results inside the class function? e.g I have a query that selects all from a table and then returns a fetch all result set. Is it possible to loop through that result set inside a classes function? e.g class query< public function show()< getResults(); while($stmt->fetchCollumn()) < ECHO RESULTS HERE >

The sample you provided is not valid PHP and has a few issues:

is not a proper function declaration — you need to declare functions with the ‘function’ keyword.

The syntax should rather be:

public function scoreTest()

Second, wrapping the bigTest() and smallTest() functions in public function() <> does not make them private — you should use the private keyword on both of these individually:

class test () < public function newTest()< $this->bigTest(); $this->smallTest(); > private function bigTest() < //Big Test Here >private function smallTest() < //Small Test Here >public function scoreTest() < //Scoring code here; >> 

Also, it is convention to capitalize class names in class declarations (‘Test’).

class test < public newTest()< $this->bigTest(); $this->smallTest(); > private function bigTest() < //Big Test Here >private function smallTest() < //Small Test Here >public scoreTest() < //Scoring code here; >> 

I think you are searching for something like this one.

class test < private $str = NULL; public function newTest()< $this->str .= 'function "newTest" called, '; return $this; > public function bigTest()< return $this->str . ' function "bigTest" called,'; > public function smallTest()< return $this->str . ' function "smallTest" called,'; > public function scoreTest()< return $this->str . ' function "scoreTest" called,'; > > $test = new test; echo $test->newTest()->bigTest(); 

To call any method of an object instantiated from a class (with statement new), you need to «point» to it. From the outside you just use the resource created by the new statement. Inside any object PHP created by new, saves the same resource into the $this variable. So, inside a class you MUST point to the method by $this. In your class, to call smallTest from inside the class, you must tell PHP which of all the objects created by the new statement you want to execute, just write:

Читайте также:  Таблицы

Источник

How to call a function or method inside its own class in php?

I declare my class in PHP and several functions inside. I need to call one of this functions inside another function but I got the error that this function is undefined. This is what I have:

4 Answers 4

This is basic OOP. You use the $this keyword to refer to any properties and methods of the class:

I would recommend cleaning up this code and setting the visibility of your methods (e.e. private, protected, and public)

 public function c()< $m = $this->b('Mesage'); echo $m; > > 

You can use class functions using $this

You need to use $this to refer to the current object

$this-> inside of an object, or self:: in a static context (either for or from a static method).

To call functions within the current class you need to use $this , this keyword is used for non-static function members.

Also just a quick tip if the functions being called will only be used within the class set a visibility of private

If you going to call it from outside the class then leave it as it is. If you don’t declare the visibility of a member function in PHP, it is public by default. It is good practice to set the visibility for any member function you write.

Or protected if this class is going to be inherited by another, and you want only the child class to have those functions.

protected function myfunc()<> 

Источник

Using parent variables in a extended class in PHP

I don’t get it. I would be more then happy to answer your question but it’s not clear enough. Do you want to construct «extended» like ($obj = new Extended($main)) or are you looking for static vars?

5 Answers 5

It would be easily possible with a simple constructor

 class Two extends One < function __construct() < parent::$string = "WORLD"; $this->string = parent::$string; > > $class = new Two; echo $class->string; // WORLD ?> 

EDIT: This can be solved much better with Inversion of Control (IoC) and Dependency Injection (DI). If you use your own framework or one without Dependency Injection Container try League/Container

Answer below left as history of foolish answers.

 public static function getInstance() < if (!isset(self::$_instance)) < self::$_instance = new self(); >return self::$_instance; > public function &__get($name) < return $this->_vars[$name]; > public function __set ($name, $value) < $this->_vars[$name] = $value; > > $config = Config::getInstance(); $config->db = array('localhost', 'root', ''); $config->templates = array( 'main' => 'main', 'news' => 'news_list' ); class DB < public $db; public function __construct($db) < $this->db = $db; > public function connect() < mysql_connect($this->db[0], $this->db[1], $this->db[2]); > > $config = Config::getInstance(); $db = new DB($config->db); $db->connect(); class Templates < public $templates; public function __construct($templates) < $this->templates = $templates; > public function load ($where) < return $this->templates[$where]; > > $config = Config::getInstance(); $templates = new Templates($config->templates); echo $templates->load('main') . "\n"; 

Im not going to downmod but you are really lacking in the OOP design area. You should NEVER extend Config classes — Config objects should be contained in the objects that consume them — not extended into other classes. Sorry, but this is plain silly.

Читайте также:  text-align

I don’t do that, but thats what the guy wants. It didn’t start out as a config class, but thats what it turned out to be.

Just say no to perpetuating sillyness 🙂 I don’t blame the OP at all but we should know better enough to point out that the OP made a bad design choice and it will bite him in the ass HARD if he basses his entire code structure off of this «anti-pattern» 🙂

I realize this is super-old, but in case anyone else needs a clue.

Have you considered using static variables?

The PHP OOP design pattern is such that statically declared variables in a parent class remain the same in the child class, too.

 > class B extends A < public static $test = 'b'; >$obj = new B; $obj->test(); ?> 

Running this code (on PHP 5.3- I’m sure it’s the same for other versions, too) will give you the following result:

From what I could gather in your OP, you are looking for a way for the parent class variables to remain — even in extended classes. This solves that problem.

To call the variables publicly outside of the class scope (i.e. where you’d normally write $obj->vars), you’d need to create a function in the parent class that references self::$variable_name so that it can throw that variable back to the code that utilizes either that class, or any other class that extends it.

For example, something like:

public function get_variable()

You could also create a magic method that would dynamically throw back the self::$variable based on what you ask the instance for — i.e. a method or a variable. You could wire the code to throw back the self::$variable equivalent in any case.

Read http://php.net/manual/en/language.oop5.magic.php for more info on the various magic methods that allow you to do this kind of stuff.

The OP was a bit cryptic so I wasn’t sure if that’s exactly what you wanted, but I didn’t see anyone else here reference static variables so thought I’d chime in — hope it helps!

Источник

Читайте также:  List item html css

Main function in php class

Блог веб разработки статьи | видеообзоры | исходный код

webfanat вконтакте webfanat youtube

методы классов PHP

методы классов PHP

Всем привет и сегодня мы с вами рассмотрим функции отладки которые могут получать информацию о классах, их методах и свойствах. Поехали!

Допустим у нас есть некий класс:

class Main < private $hello = "Hello world"; public function __construct() < echo $this->getParam(); > private function getParam()< return $this->hello; > > $object_Main = new Main();

здесь у нас определен класс Main и создан его объект $object_Main, в результате чего у нас выводится строчка ‘Hello world’. И мы хотим проверить действительно ли у нас существует данных класс. Сделать это можно используя функцию class_exists():

В качестве аргумента данной функции передается название класса, который мы хотим проверить на существование. И если класс существует в контексте данного документа нам возвращается true, а если нет то false. Здесь все просто.

Причем что еще важно. Регистр в названии класса не учитывается, то есть мы можем написать не Main, а mAiN и все будет работать.

Едем дальше. С помощью функции get_declared_classes() мы получим массив со всеми доступными нам классами:

echo "
"; print_r(get_declared_classes()); echo "

";

здесь вы возможно будете немного шокированы количеством классов которые нам доступны. Классы которые вы создали в контексте данного документа будут в самом конце списка этого массива.

Через созданный объект класса вы можете получить его имя:

echo get_class($object_Main);

нам вернется имя класса объекта(Main).

Мы также зная имя класса можем получить перечень его методов, используя функцию get_class_methods():

print_r(get_class_methods('Main'));

в качестве аргумента мы передаем имя класса. Здесь важно понимать что нам вернутся методы класса только с модификатором доступа public.

Однако мы с помощью функции method_exists() можем проверять наличие метода с любым модификатором в классе.

if(method_exists($object_Main,'getParam'))< echo 'Да метод существует'; >else

данной функции уже передается два параметра. Первый объект класса, второй название метода который мы проверяем на наличие. Результатом исхода будет true или false.

Чтобы получить перечень свойств класса можно воспользоваться функцией get_class_vars():

print_r(get_class_vars('Main'));

нам вернется массив свойств класса Main с модификатором доступа public.

И напоследок давайте рассмотрим еще одну функцию, которая позволяет определять название родительского класса:

if(get_parent_class('Main')) < echo "Имя родительского класса ".get_parent_class('Main'); >else

здесь мы проверили есть ли у класса Main родительский класс. В нашем случае его нет. Поэтому нам вернется false, а в другом случае возвращается имя родительского класса.

Вот в принципе и все что я хотел вам рассказать. Данными функциями в основном пользуются для отладки программного кода. Когда необходимо получить краткую и структурированную информацию о классе не углубляясь в сам код.

На этом я с вами прощаюсь и желаю удачи! Пока!

Оцените статью:

Статьи

Комментарии

Внимание. Комментарий теперь перед публикацией проходит модерацию

Все комментарии отправлены на модерацию

Реклама

Запись экрана

Данное расширение позволяет записывать экран и выводит видео в формате webm

Добавить приложение на рабочий стол

Источник

Оцените статью